4

Almost all the pipe examples I've seen advice closing the unused write/read ends. Also man clearly states that pipe() creates a pipe, a unidirectional data channel But I've tried reading and writing to both ends of the pipe in both the parent and the child and everything seems to be OK.

So my doubt is why do we need 2 pipes if two processes have to both read and write to each other and why not do it using a single pipe?

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
  • 1
    Because the guys that first implemented pipe() made it uni-directional, which then became a standard for subsequent implementations. (Note that on some OS's pipe() does give you a bi-directional stream, while others does not). Just use 2 pipes or use socketpair() if you need bi-directional communication. – nos Apr 13 '12 at 13:35
  • The guys that first implemented pipe() equipped the pipe with only a single buffer, akin to real-world pipes for fluid/gas conveyance. For dual buffers, see sockets. – jørgensen Apr 13 '12 at 13:50
  • Solaris' pipes are bidirectional. Not that a whole lot of people are using Solaris anymore... just throwing it out there. But, as others have made clear, if you want portability, you should not assume that capability. – FatalError Apr 13 '12 at 13:53

2 Answers2

8

If you use the same pipe how does the child separate its messages from the parents messages and vice versa?

For example:

Parent writes to pipe
Parent reads from pipe hoping to get message from child but gets its own message :(

It is much easier to use one pipe for child->parent and another pipe for parent->child.

Even if you have some protocol for reading/writing it is quite easy to deadlock the parent and child process.

benmmurphy
  • 2,503
  • 1
  • 20
  • 30
5

You can read and write at both ends of the created pipe, but uni-directional means that data only travels in one direction at any time, from parent to child or vice versa. Two pipes are needed for non-blocking sending and receiving of data, meaning that you can read and write at the same time with two pipes, but with one pipe you must finish reading before you can write to the pipe or you must finish writing something before you can read the pipe. In layman terms, you can only read or write at any point of time with only one pipe

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
A Person
  • 1,350
  • 12
  • 23