I'm trying to learn how to work with fork()
to create new processes and pipes
to communicate with each process. Let's say I have a list that contains 20 words, and I create 3 processes. Now, I need to distribute the words between the processes using pipes, and the each process will sort the list of words it receives. The way I want to achieve this is like this:
Word1 => Process1
Word2 => Process2
Word3 => Process3
Word4 => Process1
Word5 => Process2
Word6 => Process3
.
.
.
So each process will have a list of words to sort, and eventually I'll use MergeSort to merge all the sorted lists returned by each process. I'm not sure how to use pipes to communicate with each process (e.g. feed each process with a word). Any help that would put me on the right track would be appreciated.
The overall picture is usually:
Duplicate the pipe part for communicating back from child to parent. Be careful not to deadlock when parent and child are trying to communicate in both directions simultaneously.
Try this code for size. It uses a fixed number of child processes, but you can change that number by adjusting the enum
MAX_KIDS
(it was mostly tested with that set at 3; I later changed it to 5 just to make sure).There's nothing magical about pipes - they are just a communication medium with two endpoints. The logic goes approximately:
Create 3 pipes and hold onto one endpoint. Fork three times, and get each of those forked children to hold onto the other end of the pipe. The child then goes into a read loop, waiting for input and writing back output. The parent can round-robin all outputs, then do a round-robin read of inputs. This isn't the nicest strategy, but it's by far the simplest. i.e.,
A given child just looks like this:
The next step would be doing your read-back in the parent process in an asynchronous, non-blocking manner (possibly using
select
, or just a busy-wait polling loop). This requires the children to report back which task they are returning a result for, because the ordering could get messy (i.e., you can no longer rely on the first work unit you send being the first response you get). Welcome to the fun world of concurrency bugs.Given the somewhat underspecified nature of your question, I hope this is somehow useful.