我最近使用 sysinfo systemcall 编写了以下 C 代码来显示系统统计信息,让我感到有趣的是 sysinfo 结构的 freeram 变量不返回可用 RAM 的数量,而是返回当前的 RAM 使用情况。我不得不使用一种变通方法通过从 totalram 中减去 freeram 来显示正确的值。我试过用谷歌搜索这个特定的变量,但无济于事。对这种奇怪行为的任何洞察都会非常有帮助。
/*
* 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;
}