Fork rule #5 – racing

Notice the #if 1 and #endif surrounding the sleep(2); statement in the previous code (ch10/fork5.c)? It of course implies that the code will be compiled and thus run.

What if we change the #if 1 to #if 0 ? It's obvious, the sleep(2); statement is effectively compiled out. Let's do this: rebuild and re-run the fork5 program. What will now happen?

Think about this: fork rule #4 tells us the story. After the fork, we will still have the child and parent processes working on separate copies of the data variables; hence, the values we saw earlier will not change.

However, this time, there is no sleep to crudely synchronize the parent and child; thus, the question arises, will the printf for the child or parent code (displaying ...

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.