1
votes

I am reading about the pipes in UNIX for inter process communication between 2 processes. I have following questions.

1) Is Unix pipe limited to use only between 2 processes or can we use 3 or more related processes to communicate using a single pipe? For example, if I have one parent & 2 child processes, Can I use the pipe to write from the parent process and can I read using the same pipe from both children? If that is the case how both children will get same contents because if one child reads from the pipe, the data will be removed from the pipe by kernel?

2) Is it really necessary to close the unused end of the pipe? for example, if my parent process is writing data in to the pipe and child is reading from pipe, is it really necessary to close the read end of the pipe in parent process and close the write end from child process? Are there any side effects if I won't close those ends? Why do we need to close those ends?

1
You can have as many consumers as you want but only one consumer can read the message from the pipe. If both children attempts to read from the pipe, the first one will get the message while the other will get blocked. If you want the same message received by multiple recipient, look at multicast and broadcast. You can also unicast but you have to send to each connected clients. Try unix domain socket. The options are endless, use your imagination. YMMV - alvits
2) You need to close the writing end in the reader because otherwise you'll be stuck reading forever - as long as there is a writing fd, you don't know if data will come some day... The writer instead had better close its reading end, otherwise what may happen is that eg the reading process dies, the writing process doesn't notice (there still exists a reading fd after all!) and when the pipe buffer (which is small) fills up subsequent write()s will block because noone is depleting the pipe. - loreb

1 Answers

1
votes

A single pipe is not a natural solution to allowing a parent broadcast to its children. Shared memory would provide a more natural method to solve that problem. There is only one message that is naturally broadcast from the parent to the children: the parent can close the write end of the pipe and cause all the children to see a read return 0 on the read end of the pipe.

However, a single pipe can be used by children to relay information back to the parent. So long as the messages are properly framed with source information from the child, the parent can field responses from all its children from the read end of the pipe, while each child writes to the write end of the pipe.