Question

Trying to clear up my understanding of fork() and pipe(). I understand that a pipe() is a unidirectional way to transfer data between two processes. If in the parent process, I call pipe() on a two integer array, and then I fork it, does this effectively create two pipes that allow me to transfer data bidirectionally? (i.e. have the parent read from standard in and the child write to standard out, or similarly have the parent write to standard out and the child read from standard in?)

Was it helpful?

Solution

No. There is always only one pipe after you call pipe() once. However, what fork() does is that it copies everything including the file descriptor table to the child process. So the parent and the child will both have access to the ONLY two ends of the pipe. That's why you should close the unused end in parent and child, i.e. if you are trying to write in parent and read in child, you should close fd[0] in parent and fd[1] in child - because you can only push from one side to another in a pipe! Think of it as a real pipe, what would happen if you pour water into the both ends of the pipe.

OTHER TIPS

The answer is "no". The result of fork() is that each of the descriptors returned by pipe() is duplicated (i.e., like dup()), but the pipe itself is the same pipe for both parent and child. Writing to the write end of the pipe will make data available on the read end, but parent and child have the same read end.

If you need bidirectional communication, you can call pipe() twice. Alternatively, you can call socketpair() to create a pair of sockets that support bidirectional communication.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top