Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
In Section 24.5, we looked at how signals could be used to synchronize the actions of parent and child processes in order to avoid race conditions. Pipes can be used to achieve a similar result, as shown by the skeleton program in Example 44-3. This program creates multiple child processes (one for each command-line argument), each of which is intended to accomplish some action, simulated in the example program by sleeping for some time. The parent waits until all children have completed their actions.
To perform the synchronization, the parent builds a pipe before creating the child processes
. Each child inherits a file descriptor for the write end of the pipe and closes this descriptor once it has completed its action
. After all of the children have closed their file descriptors for the write end of the pipe, the parent’s read()
from the pipe will complete, returning end-of-file (0). At this point, the parent is free to carry on to do other work. (Note that closing the unused write end of the pipe in the parent
is essential to the correct operation of this technique; otherwise, the parent would block forever when trying to read from the pipe.)