Sunday, July 31, 2011

Getting (approx?) memory usage information on linux

Here's the code for doing so: (Tested on Ubuntu 10.10)

#include <unistd.h>
#include <stdio.h>
int processMemUsage() {
    int vm = 0;
    FILE* fp = fopen("/proc/self/stat", "r");
    if(fp == NULL) {
        return vm;
    }
    int dummy;
    char cmd[128], state[8];
    fscanf(fp, "%d%s%s%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d",
           &dummy, cmd, state, &dummy, &dummy, &dummy, &dummy,
           &dummy, &dummy, &dummy, &dummy, &dummy, &dummy,
           &dummy, &dummy, &dummy, &dummy, &dummy, &dummy,
           &dummy, &dummy, &dummy);
    unsigned long vmSize;
    fscanf(fp, "%lu", &vmSize);
    fclose(fp);
    vm = (int) (vmSize >> 10);
    return vm;
}

Hope this helps!

No comments:

Post a Comment