sysinfo system call not returning correct freeram value

k4rtik picture k4rtik · Jan 24, 2012 · Viewed 8.9k times · Source

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

Answer

R.. GitHub STOP HELPING ICE picture R.. GitHub STOP HELPING ICE · Jan 24, 2012

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.