sysinfo system call not returning correct freeram value

心不动则不痛 提交于 2019-12-01 21:15:21

问题


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;
}

回答1:


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.




回答2:


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.




回答3:


you need to multiply by mem_unit.



来源:https://stackoverflow.com/questions/8987636/sysinfo-system-call-not-returning-correct-freeram-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!