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
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.,
while there is work left to do:
for i in 1..3
write current work unit to pipe[i]
for i in 1..3
read back response from pipe[i]
A given child just looks like this:
while(input = read from pipe)
result = do work on input
write result to pipe
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.