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 the variable values) run first? In other words, the question we are really asking is this: in the absence of any kind of synchronization primitive, after the fork(2), which process will get the processor first: parent or child? The short answer is the next rule:

Fork rule #5: After the fork, the order of execution between the parent and child process is indeterminate.

Indeterminate? Well, this is a fancy way to say we really have no idea or it's unpredictable. So that is the deal: the systems developer should not try to predict the order of execution. Running the modified fork5 (no sleep(2) statement) now:

$ ./fork5 
Parent process, PID 18620:
loc=7 g=8
Parent (18620) will exit now...
Child process, PID 18621:
loc=9 g=6
Child (18621) done, exiting ...
$

Ah, the parent ran first. That does not really mean anything! The parent might run first the next 50,000 times you try it out, but on the 50,001st trial run, the child process may run first. Leave it alone: it's unpredictable.

This leads us to another key point (common in software): We have what's called a race condition here. A race is literally what it says: we cannot predict with certainty who will be the winner. In the previous program, we really don't care whether the parent or child process wins the race (runs first): this is called a benign race condition. But often in software design we do actually care; in such cases, we need a way to guarantee the winner. In other words, to defeat the race. This is called synchronization. (As mentioned earlier, we shall address this point in detail later in this chapter.)

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

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