From 3e1d1e2ae1e5023c03140018486e6f14d37a4b05 Mon Sep 17 00:00:00 2001 From: yuqing Date: Mon, 2 Nov 2015 16:19:49 +0800 Subject: [PATCH] add function get_sys_total_mem_size, ONLY support Linux and FreeBSD --- HISTORY | 3 ++- src/shared_func.c | 47 ++++++++++++++++++++++++++++++++++++++++++++++- src/shared_func.h | 7 +++++++ 3 files changed, 55 insertions(+), 2 deletions(-) diff --git a/HISTORY b/HISTORY index 40a4eba..40b795c 100644 --- a/HISTORY +++ b/HISTORY @@ -1,9 +1,10 @@ -Version 1.23 2015-10-30 +Version 1.23 2015-11-02 * sched_thread.c: task can execute in a new thread * sched_thread.c: support delay tasks * add function get_current_time_us and get_current_time_ms * mblock add stat function + * add function get_sys_total_mem_size, ONLY support Linux and FreeBSD Version 1.22 2015-10-10 * export php function: fastcommon_get_first_local_ip diff --git a/src/shared_func.c b/src/shared_func.c index 73407c8..83b57e6 100644 --- a/src/shared_func.c +++ b/src/shared_func.c @@ -24,10 +24,19 @@ #include #include #include + #include "shared_func.h" #include "logger.h" #include "sockopt.h" +#ifdef OS_LINUX +#include +#else +#ifdef OS_FREEBSD +#include +#endif +#endif + char *formatDatetime(const time_t nTime, \ const char *szDateFormat, \ char *buff, const int buff_size) @@ -2259,7 +2268,7 @@ int64_t get_current_time_us() { logError("file: "__FILE__", line: %d, " \ "call gettimeofday fail, " \ - "errno=%d, error info: %s", \ + "errno: %d, error info: %s", \ __LINE__, errno, STRERROR(errno)); return errno != 0 ? errno : EPERM; } @@ -2267,3 +2276,39 @@ int64_t get_current_time_us() return ((int64_t)tv.tv_sec * 1000 * 1000 + (int64_t)tv.tv_usec); } +int get_sys_total_mem_size(int64_t *mem_size) +{ +#ifdef OS_LINUX + struct sysinfo si; + if (sysinfo(&si) != 0) + { + logError("file: "__FILE__", line: %d, " \ + "call sysinfo fail, " \ + "errno: %d, error info: %s", \ + __LINE__, errno, STRERROR(errno)); + return errno != 0 ? errno : EPERM; + } + *mem_size = si.totalram; + return 0; +#else +#ifdef OS_FREEBSD + int mib[2]; + size_t len; + + mib[0] = CTL_HW; + mib[1] = HW_MEMSIZE; + len = sizeof(*mem_size); + if (sysctl(mib, 2, mem_size, &len, NULL, 0) != 0) { + logError("file: "__FILE__", line: %d, " \ + "call sysctl fail, " \ + "errno: %d, error info: %s", \ + __LINE__, errno, STRERROR(errno)); + return errno != 0 ? errno : EPERM; + } + return 0; +#else +#error port me! +#endif +#endif +} + diff --git a/src/shared_func.h b/src/shared_func.h index 1256063..bd9cf48 100644 --- a/src/shared_func.h +++ b/src/shared_func.h @@ -528,6 +528,13 @@ int64_t get_current_time_us(); #define get_current_time_ms() (get_current_time_us() / 1000) +/** get system total memory size + * parameters: + * mem_size: return the total memory size + * return: error no , 0 success, != 0 fail +*/ +int get_sys_total_mem_size(int64_t *mem_size); + #ifdef __cplusplus } #endif