Pipe is the easiest form of UNIX interprocess communication, but there is a few tips to be remembered before using it.
Pipes inside a single process is basically useless; therefore we usually do piping with
fork(). And here comes one important concept: pipes can only help RELATED processes communicate, meaning only processes that forked or created by the same ancestor can communicate using pipes. Non-related processes can communicate with each other by other forms of channel like shared memory or sockets.If you want
n processes to communicate through pipes, you'll need at least n-1 different pipes. This is because one pipe can only connect two processes.So how do with use pipes with forks? First you need to create all the pipes (using
pipe()) you need in the 'oldest' parent before any forking occurs. This way all the pipes created get inherited by all the descendants. A bit of caution here: 'pipes get inherited' meaning that all the file descriptors have their distinct copies for each child process; however, each copy actually refers to the SAME file (an end/terminal of a pipe/channel in the kernel); in other words, the channel inside the kernel does not have copies, the channel is the channel, both ends of the channel are referenced/referred by several copies of file descriptors having identical names.So now you can do forks. But how? different ways of forking creates different architecture/processes tree. If you want to create a pipeline among a series of processes, it is better you use a 'chain' of processes architecture. For reference (a nice one), check this out: http://tinyurl.com/2fonwzn.
After the necessary setup mentioned in the previous paragraphs, you need to do some necessary 'closing' (
close()) and 'duping' (dup2()) in each child process to actually make each pipe works correctly.To visualize the concepts mentioned above, here is a link: http://tinyurl.com/6xx88e.
No comments:
Post a Comment