sysinfo returns incorrect value for freeram (even with mem_unit)

瘦欲@ 提交于 2019-12-23 02:43:10

问题


My full C MATE applet can be found at github here: https://github.com/geniass/mate-resource-applet/tree/cmake (BRANCH CMAKE). It's a hacky mess right now, so see the code below.

I couldn't find an applet to display my computer's free ram, so that's basically what this is. I am using sysinfo to get this information, and it works fine for my system's total ram (roughly 4GB, it shows 3954 MB). htop shows 3157 MB used of 3954 MB.

However, the value sysinfo gives for free ram (136 MB) is obviously wrong (if free ram is ram that hasn't been allocated or something, I don't know).

This question is the same problem, but the solution, involving mem_unit, doesn't work because mem_unit = 1 on my system.

Here's a minimal program that gives the same values:

#include <stdio.h>
#include <sys/sysinfo.h>


int main() {
    /* Conversion constants. */
    const long minute = 60;
    const long hour = minute * 60;
    const long day = hour * 24;
    const double megabyte = 1024 * 1024;
    /* Obtain system statistics. */
    struct sysinfo si;
    sysinfo (&si);
    /* Summarize interesting values. */
    printf ("system uptime : %ld days, %ld:%02ld:%02ld\n", 
            si.uptime / day, (si.uptime % day) / hour, 
            (si.uptime % hour) / minute, si.uptime % minute);
    printf ("total RAM   : %5.1f MB\n", si.totalram / megabyte);
    printf ("free RAM   : %5.1f MB\n", si.freeram / megabyte);
    printf ("mem_unit:   : %u\n", si.mem_unit);
    printf ("process count : %d\n", si.procs);
    return 0;
}

Output:

system uptime : 0 days, 10:25:18
total RAM   : 3953.9 MB
free RAM   : 162.1 MB
mem_unit:   : 1
process count : 531

What's going on here? Is freeram not what I think it is?


回答1:


Linux doesn't like when free memory is used nowhere. So when there is free memory available, it takes it temporarily as cache memory and buffers. The free memory seems very low, but as soon as a program requires memory, Linux reduces its cache / buffers usage and give the program what it wants.

The Linux command free -m displays the state of the memory, cache and buffers.

See this link for example and detailed information.



来源:https://stackoverflow.com/questions/14345937/sysinfo-returns-incorrect-value-for-freeram-even-with-mem-unit

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