wcwswswws
wcwswswws

Reputation: 29

Does any lib or tools can calculate the cpu usage and some other parameters for different process in C/C++ under Linux?

Now my project is based on multi-process and I try to calculate the some parameters of each process, such as cpu usage, io usage. I use C++ and my project runs under Linux. Does any lib or open source project can solve it?

Upvotes: 0

Views: 67

Answers (1)

The kernel exposes such parameters thru the /proc filesystem, see proc(5) for more.

Files inside /proc/ are usually textual files and should be read sequentially (they are generated on the fly like pipes; often stat(2) on them gives a 0 meaningless size). Reading these pseudo-files does not involve any disk I/O so is really quick.

Try for instance the following commands:

 cat /proc/self/maps
 cat /proc/$$/status

For instance, to get the program size progsize (actually process size) of a process of pid pid you might do:

 long progsize= -1;
 pid_t pid = something();
 char path[32];
 snprintf (path, sizeof(path), "/proc/%d/statm", (int) pid);
 FILE *fil = fopen(path, "r");
 if (fil) {
   fscanf(fil, "%ld", &progsize);
   fclose(fil);
 } else { perror(path); exit(EXIT_FAILURE); };

You might want to parse /proc/1234/stat for timing (and resident set size, i.e. used RAM, etc etc...) information of pid 1234.

For your finished child processes, use also wait4(2) which fills a struct rusage about the child process, see also getrusage(2)

Upvotes: 1

Related Questions