fork()
creates a new process which is almost the exact copy of the one that makes the call. The newly created process is called the child. Beware that exact copy is a strong assumption! That really means that the newly created process is at the time of its creation in the exact state of its parent (this is a slightly rough assumption, but for the sake of simplicity think of it as is). Then one process makes a call to fork
and then two processes return from the call! fork
is a kind of cloning machine (one sheep enters, and then two exit from the machine!). Normally you should test the returned value of fork
(see man for details).
Then from now two processes are running independently!
One does a call to wait
, while the other does the same on its own. Effect of wait
is different in both. For the original process, wait
will wait for the child to terminate and then capture information about that event. The child calls wait
but as it has no child wait
does nothing and returns immediately. It then print the value of its variable n
which as not been modified: 5
. And then it exit
s with a value 0. So it terminates. This will permit the parent process to awake from it's wait
call and capture the exit value of its child (0). It then prints it 0
and exit
s.
Beware that some variants of this scenario may happen, while this will not change the observable behavior, concurrent runs may run differently.