views:

503

answers:

4

I need to get the memory usage of the current process in C. Can someone offer a code sample of how to do this on a Linux platform?

I'm aware of the cat /proc/<your pid>/status method of getting memory usage, but I have no idea how to capture that in C.

BTW, it's for a PHP extension I'm modifying (granted, I'm a C newbie). If there are shortcuts available within the PHP extension API, that would be even more helpful.

+10  A: 

The getrusage library function returns a structure containing a whole lot of data about the current process, including these:

long   ru_idrss;         /* integral unshared data size */
long   ru_isrss;         /* integral unshared stack size */
caf
Unfortunately the ru_idrss and ru_isrss data isn't availabe to my kernel (Ubuntu Hardy): http://linux.die.net/man/2/getrusage
scotts
+5  A: 

You can always just open the 'files' in the /proc system as you would a regular file (using the 'self' symlink so you don't have to look up your own pid):

FILE* status = fopen( "/proc/self/status", "r" );

Of course, you now have to parse the file to pick out the information you need.

Charles Bailey
+2  A: 
#include <sys/resource.h>
#include <errno.h>

errno = 0;
struct rusage* memory = malloc(sizeof(struct rusage));
getrusage(RUSAGE_SELF, memory);
if(errno == EFAULT)
    printf("Error: EFAULT\n");
else if(errno == EINVAL)
    printf("Error: EINVAL\n");
printf("Usage: %ld\n", memory->ru_ixrss);
printf("Usage: %ld\n", memory->ru_isrss);
printf("Usage: %ld\n", memory->ru_idrss);
printf("Max: %ld\n", memory->ru_maxrss);

I used this code but for some reason I get 0 all the time for all 4 printf()

Jeff
A: 

The above struct was taken from 4.3BSD Reno. Not all fields are mean- ingful under Linux. In linux 2.4 only the fields ru_utime, ru_stime, ru_minflt, and ru_majflt are maintained. Since Linux 2.6, ru_nvcsw and ru_nivcsw are also maintained.

http://www.atarininja.org/index.py/tags/code

mellthy