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:\n", 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 ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.