Reputation: 5376
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?
Upvotes: 2
Views: 412
Reputation: 70402
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.
Upvotes: 1