Question

I need to monitor a section of code that includes a fork and I want to confirm that clock_gettime() is documented as working for this scenario.

Here is the pseudo code:

starttime = clock_gettime()

if (fork() == 0) {
   /* in the child */
   endtime = clock_gettime()
   print "elapsed time is " endtime - starttime
}

I can find example code where this technique is used, but I am concerned that the clock will get reset during the fork, and then the subtraction of endtime and starttime will be meaningless.

This description of fork() mentions reseting some timers, but does not mention how those timers are related to clock_gettime(). By omission, one could assume that it is not affected, but I would like a bit more assurance before I rely on this technique. http://man7.org/linux/man-pages/man2/fork.2.html

I can write a test program to find out what happens, but I am more interested in finding the documentation on what is defined as the correct behavior.

EDIT: I plan in using CLOCK_PROCESS_CPUTIME_ID and CLOCK_MONOTONIC_RAW

EDIT 2: I can see in the fork man page that the cpu counters associated with times(2) are reset, but I don't see where the counters for clock_gettime() are reset. I don't see where it is documented that clock_gettime() uses the times(2) counters. If it did, I would think that times(2) would be referenced on the clock_gettime man page.

Was it helpful?

Solution

The correct behavior is for endtime in the child to be a small, close-to-zero value if you use CLOCK_PROCESS_CPUTIME_ID, since fork sets it to zero for the child. For the parent, it will be a value slightly larger than, but almost identical to starttime.
This is well-documented in the fork(2) manpage, and it is what makes sense too -- you create a new process. The new process has, of course, not consumed any CPU time. It's a newborn process, after all! The parent, on the other hand, has already consumed noticeable CPU and continues doing so, there is no good reason why its counter should be reset to zero (that would be a lie).

Other clocks like CLOCK_REALTIME or CLOCK_MONOTONIC will not be affected (the former can independently of you forking be modified by a privilegued user, but the latter cannot).
That, too, is according to what common sense tells you. They're global timers, if forking a new process (which happens nearly all the time) was interfering with them, it would be a desaster.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top