0

How can I measure the memory used by a child process after I call fork and exec? Basically I want to be able to write code that corresponds to the following

if (!fork()) {

    // run child process
    exec();
} else {

    while (child active) {
        print memory used by child
    }
}

There are two things that I do not know here, how can I see if the child process has finished running? Will I have to use some sort of process level mutual exclusion here? If yes then what is a structure I can use? Can I just use the OS filesystem for this purpose?

Also I was looking at the answer at this link Differences between fork and exec, in paragraph 8 the author says copy on write is useful when process calls fork without calling exec. But isn't this true more in the case when the parent calls fork and does not call exec? When the parent calls exec the virtual address space of the child is wiped out and replaced with the one resulting from the new program loaded into memory correct?

Thank you!

Community
  • 1
  • 1
Curious
  • 20,870
  • 8
  • 61
  • 146
  • 3
    Use only the C or C++ tag; they are different languages. The fork tutorial should mention `wait`, the function you use to tell if your child has died or not. Checking a child process' used memory is the same as checking any other process' memory (ex. `/proc`) – Colonel Thirty Two Dec 13 '15 at 05:49
  • Thank you! I was not aware of the /proc directory. Is there a on blocking way to check if the child has died? Removed the tags! I intended to use the C++ tag but accidentally added both... – Curious Dec 13 '15 at 05:51
  • Use the `WNOHANG` argument. See [`man 2 wait`](http://linux.die.net/man/2/wait) – Colonel Thirty Two Dec 13 '15 at 05:52
  • Another way to do the non-block check in certain circumstances is: `kill(child_pid,0)` and look for the `ESRCH` error – Craig Estey Dec 13 '15 at 05:55
  • Also how do I check memory usage in the proc directory? – Curious Dec 13 '15 at 05:56

1 Answers1

1

Regarding the above comment chain which I evidently can't reply to because I don't have 50 rep:

The return value of fork in the parent if successful is the PID of the child. You should probably save the return value so you can
1. wait on the correct child (if you have more than one), and
2. see if fork fails (in which case you probably don't want to loop until the child exits ).

You could also use signals to figure out when the child dies instead of continuously trying to wait with the WNOHANG option. The process will send SIGCHLD to the parent when it terminates (or stops) and if it died then you can wait on it with waitpid and stop your loop. see:
man 7 signal
man 2 sigaction
for more information on this.

regarding memory usage, it seems you either want /proc/[pid]/statm or /proc/[pid]/stat.

man 5 proc will give you all the information about what is in those files.