问题描述
我最近使用 sysinfo 系统调用编写了以下 C 代码来显示系统统计信息,让我感到有趣的是 sysinfo 结构的 freeram 变量不返回可用 RAM 的数量,而是返回当前的 RAM 使用情况.我不得不使用一种变通方法通过从 totalram 中减去 freeram 来显示正确的值.我试过用谷歌搜索这个特定的变量,但无济于事.对这种奇怪行为的任何洞察都会非常有帮助.
I recently wrote the following C code using sysinfo systemcall to display system statistics, what amused me was that the freeram variable of sysinfo structure doesn't return the amount of free RAM instead it is returning the current RAM usage. I had to use a workaround to show the correct value by subtracting freeram from totalram. I have tried googling about this specific variable but to no avail. Any insight into this weird behavior would be really helpful.
/*
* 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
", info.uptime/3600, info.uptime%3600/60, info.uptime%60);
printf("Total RAM: %ld MB
", info.totalram/1024/1024);
printf("Free RAM: %ld MB
", (info.totalram-info.freeram)/1024/1024);
printf("Process count: %d
", info.procs);
printf("Page size: %ld bytes
", sysconf(_SC_PAGESIZE));
return 0;
}
推荐答案
移除
#include "syscalls.h"
可能是,您从某个地方借用了代码并进行了编辑.双引号用于导入非官方的头文件.那个自定义头文件并不是真正需要的.
May be, you borrowed the code from somewhere and edited. Double quotes are used to import unofficial header files. That custom header file is not really required.
不需要.您的代码将运行良好.
It's not needed. You code will run fine.
在我的电脑上,$free -m
的 freeram 值与程序的 info.freeram 匹配.显然,freeram 并不是你想象的那样.
On my PC, freeram value of $free -m
matches with info.freeram of the program. Apparently, freeram is not what you think it's showing.
阅读更多关于 http://www.redhat.com/advice/tips/meminfo.html
MemFree 是空闲内存 &MemFree + Buffers + Cached 是可用内存(你想要的).所以,你只是错误地理解了 freeram 这个词.
MemFree is the free memory & MemFree + Buffers + Cached is available memory (which you want). So, you are just understanding the term freeram wrongly.
这篇关于sysinfo 系统调用未返回正确的 freeram 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!