Defeating the race after fork

Recall the example code we saw earlier in chapter ch10/fork5.c. In this program, we artificially, and crudely, waited for the child process by introducing a sleep(2); statement in the parent's code:

[...]   
default: /* Parent */
#if 1
sleep(2); /* let the child run first */
#endif
printf("Parent process, PID %d: ", getpid());
[...]

This is not good enough: What if the child process takes longer than two seconds to complete its work? If it takes just a few milliseconds, then we unnecessarily waste time. 

This is how we resolve the race: Who will run first, the parent or the child? Clearly, fork rule #5 tells us that it's indeterminate. But, in real-world code, we need a way to guarantee that one of them indeed runs first—say, the child process. With the wait API, we now we have a proper solution! We change the preceding code snippet to this:

[...]   
default: /* Parent */
wait(0); /* ensure the child runs first */
printf("Parent process, PID %d: ", getpid());
[...]

Think about how this works: After the fork, it's a race: If the child process does run first, then no harm is done. However, at some point in the near future, the parent process will get the CPU; that's fine as all it does is block upon the child by calling wait. If the parent does run first after the fork, the same thing occurs: it blocks upon the child by calling wait. We have effectively defeated the race! By issuing the wait as the first thing done in the parent process after fork, we effectively guarantee that the child runs first.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset