开发者

Looking for something like getrusage() in C++

getrusage() can display the amount of memory used by the children of a process. I am creating a shell from which I will launch several child programs. getrusage() will report the total sum of memory all of these chi开发者_StackOverflow社区ldren are using, which is not what I want. I want to know how much memory each child is using. getrusage() looks like something I would like to use except it doesn't work for individual child processes. What is like it that can be used?


Maybe you could fork off the children one at a time and then use getrusage(RUSAGE_CHILDREN...) to find out each child's usage independently.

The most obvious drawback to this approach is if the children need to be running simultaneously. In that case, a custom-written intermediary program could do it. Instead of executing the children directly, execute a program which:

  • forks
  • execs the requested program, perhaps passed as command line arguments (program and its arguments) in the style of the nice or time commands
  • the parent executes getrusage() for its children. Since there is only one, it is the desired result. Then use some mechanism to pass the information back to the main program, perhaps a status file.

Then all that's needed is for the master to fork off each of its children through the intermediary which is directed to run the intended child and report memory usage.

The point is to rejigger the hierarchy of child processes so that the program calling getrusage() has only one child. The master program can't because it has too many children and there is no system call to get memory usage by pid.

I suppose you could also snoop around in /proc/<pid>/mem as well, if this is Linux or a compatible.


You can use wait3 or wait4, as detailed in this other SO thread: CPU time after the process finished.


When you fork() each child process, the parent gets the PID. You can use this to query the /proc filesystem, specifically /proc/{pid}/status (and possibly others, depending on which specific metrics you're after).

This will give you various information, including:

VmSize:    2788 kB
VmLck:        0 kB
VmRSS:     1280 kB
VmData:     252 kB
VmStk:       16 kB
VmExe:      268 kB
VmLib:     2132 kB
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜