Use pipe and fork to set up the pipeline. The first process feeds the numbers 2 through 35 into the pipeline. For each prime number, you will arrange to create one process that reads from its left neighbor over a pipe and writes to its right neighbor over another pipe.
use pipes to transmit prime numbers
I set up a state machine for all child processes:
Note:
What does main process do?
This process just creates the first process, set up a pipe. Then it sends 2~35 to the pipe and close the reading end p[0]
How to setup the pipe?
Before fork()
, the process creates a pipe. After fork()
, child closes the writing end p[1]
, and parent closes the reading end p[0]
. This guarantees that only one process has the writing fd of each pipe.
How does the process terminate?
After the main process closes the writing end, the first child will read from a pipe that has no writing end, which returns 0. Then the process jumps off the while loop and closes its own writing end, so the same process will happen on its child too. Finally, the last process terminates. And all waiting parent processes will terminate one by one in the reversed order.