我使用 sysinfo
来获取内存信息。但结果似乎是错误的,因为它与/proc/meminfo
不一致。
我的代码:
#include <stdio.h>
#include <sys/sysinfo.h>
double megabyte = 1024 * 1024;
long
get_free_mem() {
struct sysinfo si;
int error = sysinfo(&si);
printf("code error=%d\n",error);
printf("available: %lu\n", si.freeram );
printf("total: %lu\n", si.totalram);
printf("mem_unit: %u \n", si.mem_unit);
return 0;
}
int main(int argc, char* argv[])
{
get_free_mem();
return 0;
}
输出信息为:
$./get_mem
code error=0
available: 67733753856
total: 135443968000
mem_unit: 1
但是 /proc/meminfo
显示:
$cat /proc/meminfo
MemTotal: 8388608 kB
MemFree: 4790464 kB
Buffers: 0 kB
Cached: 3042084 kB
并且免费
显示:
$free -m
total used free shared buffers cached
Mem: 8192 3513 4678 0 0 2970
-/+ buffers/cache: 543 7648
Swap: 1952 0 1952
很明显我的代码有问题,因为我的服务器上确实没有 135443968000 字节(将近 126 Gb,太大了)。
内核:
Linux my_hostname 2.6.32-220.23.2.ali1113.el5.x86_64 #1 SMP Thu Jul 4 20:09:15 CST 2013 x86_64 x86_64 x86_64 GNU/Linux
最佳答案
要获得正确的内存值,比如总 RAM,您需要乘以 si.total
和 si.memunit
然后除以 1024。
Free RAM、Buffer RAM 等也是如此。
编辑:将 memunit 设置为 1 没有任何问题。
关于c - Linux C : sysinfo get bad memory values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28760246/