/* usage: memwatch [commandline] */ /* make sure the first argument (the program to run) is given with full * path. This will fork a second process that uses /proc/[pid]/statm to * calculate the maximum resident memory size the other process has in * his life time. This only works on Linux. */ #include #include #include int main(int argc,char* argv[],char* envp[]) { char fn[100]; FILE* f; pid_t p=fork(); unsigned long max=0; struct timespec ts,tmp; ts.tv_sec=0; ts.tv_nsec=100000000; if (p==-1) { perror("fork failed"); return 1; } if (p!=0) { // do the exec in the parent, so time memwatch ls shows ls, not memwatch execve(argv[1],argv+1,envp); perror("execve failed"); return 1; return 0; } sprintf(fn,"/proc/%u/statm",getppid()); for (;;) { unsigned int a,b,c,d,e,f,g; FILE* F=fopen(fn,"r"); if (!F) break; // "7773 734 465 297 0 275 0" if (fscanf(F,"%u %u %u %u %u %u %u",&a,&b,&c,&d,&e,&f,&g)<6) break; fclose(F); if (b>max) { // fprintf(stderr,"new max %u\n",b); max=b; } nanosleep(&ts,&tmp); if (b==0) break; } fprintf(stderr,"max: %'.3f MB\n",max*4/1024.0); // in K }