http://unix.stackexchange.com/questions/33381/getting-information-about-a-process-memory-usage-from-proc-pid-smaps
#include <assert.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
static void show_smaps(pid_t pid) {
char cmd[1024];
snprintf(cmd, sizeof(cmd), "cat /proc/%d/smaps > /tmp/out/%d", pid, pid);
system(cmd);
}
int main() {
system("rm -rf /tmp/out; mkdir -p /tmp/out");
int i;
char* buf = malloc(10*1024*1024);
for (i=0; i<10*1024*1024; i++) {
buf[i]=1;
}
// show smaps once.
show_smaps(getpid());
pid_t pid = fork();
if (pid == 0) {
sleep(1);
show_smaps(getpid());
for (i=0; i<5*1024*1024; i++) {
buf[i]=2;
}
return 0;
} else if (pid > 0) {
sleep(2);
show_smaps(getpid());
printf("Parent pid: %d Child pid: %d\n", getpid(), pid);
assert(kill(pid, SIGTERM) == 0);
int status;
assert(wait(&status) == pid);
system("perl -E 'for my $f (</tmp/out/*>) { open my $fh, q!<!, $f; my %h; while (<$fh>) { $h{$1}+=$2 if /(Pss|Rss): +([0-9]+)/ } say qq!$f:
Rss:$h{Rss} Pss:$h{Pss}! }'");
return 0;
} else {
perror("fork failed");
return 1;
}
}
[tokuhirom@dev2 pidstatd]$ gcc -Wall stat.c
[tokuhirom@dev2 pidstatd]$ ./a.out
Parent pid: 30910 Child pid: 30916
/tmp/out/30910: Rss:10736 Pss:10347
/tmp/out/30916: Rss:10452 Pss:5186