sysinfo系统调用不返回正确的freeram值

我最近使用sysinfo systemcall编写了下面的C代码来显示系统统计信息,有趣的是sysinfo结构的freeramvariables没有返回可用RAM的数量,而是返回当前的RAM使用情况。 我不得不使用解决方法,通过从totalram中减去freeram来显示正确的值。 我试着用googlesearch这个特定的variables,但无济于事。 任何洞察这种奇怪的行为将是非常有益的。

/* * C program to print the system statistics like system uptime, * total RAM space, free RAM space, process count, page size */ #include <sys/sysinfo.h> // sysinfo #include <stdio.h> #include <unistd.h> // sysconf #include "syscalls.h" // just contains a wrapper function - error int main() { struct sysinfo info; if (sysinfo(&info) != 0) error("sysinfo: error reading system statistics"); printf("Uptime: %ld:%ld:%ld\n", info.uptime/3600, info.uptime%3600/60, info.uptime%60); printf("Total RAM: %ld MB\n", info.totalram/1024/1024); printf("Free RAM: %ld MB\n", (info.totalram-info.freeram)/1024/1024); printf("Process count: %d\n", info.procs); printf("Page size: %ld bytes\n", sysconf(_SC_PAGESIZE)); return 0; } 

去掉

 #include "syscalls.h" 

可能是,你从某处借用了代码并进行了编辑。 双引号用于导入非官方的头文件。 该自定义头文件不是真的需要。

这不是必需的。 你的代码将运行良好。

在我的电脑上, $free -m freeram值与程序的info.freeram匹配。 显然,freeram不是你想象的那样。

详细了解http://www.redhat.com/advice/tips/meminfo.html

MemFree是免费的内存和MemFree +缓冲+缓存是可用内存(你想要的)。 所以,你只是错误地理解了freeram这个词。

“免费的公羊”领域对大多数人来说毫无意义。 与真正的“免费ram”值最接近的是从/proc/meminfo获取字段,并从MemTotal减去Committed_AS 。 如果交换正在使用,结果可能是负的(这意味着有更多的内存分配比适合物理ram); 如果你想计算交换为内存,只需使用MemTotal+SwapTotal作为你的总数。

你需要乘以mem_unit。