sysinfo system call not returning correct freeram

2020-04-08 14:24发布

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\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条回答
聊天终结者
2楼-- · 2020-04-08 15:09

The "free ram" field is meaningless to most people. The closest thing to a real "free ram" value is taking the fields from /proc/meminfo and subtracting Committed_AS from MemTotal. The result could be negative if swap is in use (this means there's more memory allocated than will fit in physical ram); if you want to count swap as memory too, just use MemTotal+SwapTotal as your total.

查看更多
Evening l夕情丶
3楼-- · 2020-04-08 15:12

Remove

#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.

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.

Read more about the http://www.redhat.com/advice/tips/meminfo.html

MemFree is the free memory & MemFree + Buffers + Cached is available memory (which you want). So, you are just understanding the term freeram wrongly.

查看更多
倾城 Initia
4楼-- · 2020-04-08 15:21

you need to multiply by mem_unit.

查看更多
登录 后发表回答