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

时间:2012-01-24 13:30:16

标签: c linux operating-system system-calls sysinfo

我最近使用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;
}

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

删除

#include "syscalls.h"

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

不需要。你的代码运行正常。

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

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

MemFree是免费记忆&amp; MemFree + Buffers + Cached是可用的内存(你想要的)。所以,你只是错误地理解了freeram一词。

答案 2 :(得分:1)

你需要乘以mem_unit。