sps
sps

Reputation: 2720

Why parent process has to close all file descriptors of a pipe before calling wait( )?

I do not know why the parent process needs to close both the file descriptors of a pipe before calling wait()?

I have a C program which does:

  1. Parent creates child_a, which executes ls -l using execvp, and writes to the pipe (after closing read end of pipe).
  2. Parent creates another child (without closing any file descriptor for pipe), called child_b, which executes 'wc' by reading from pipe.(after closing write end of pipe).
  3. Parent waits for both children to complete by calling wait() twice.

I noticed that program is blocked if parent does not close both file descriptors of the pipe before calling the wait() syscall. Also after reading few questions already posted online it looks like this is the general rule and needs to be done. But I could not find the reason why this has to be done?

Why does wait() not return if the parent does not close the file descriptors of the pipe?

I was thinking that, in the worst case, if the parent does not close the file descriptor of pipe, then the only consequence would be that the pipe would keep existing (which is a waste of resource). But I never thought this would block the execution of child process (as can be seen because wait() does not return).

Also remember, parent is not using the pipe at all. It is child_a writing in the pipe, and child_b reading from the pipe.

Upvotes: 2

Views: 2125

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753595

If the parent process doesn't close the write ends of the pipes, the child processes never get EOF (zero bytes read) because there's a process that might (but won't) write to the pipe. The child process must also close the write end of the pipe for the same reason — if it doesn't, there's a process (itself) that might (but won't) write to the pipe, so the read won't return EOF.

If you duplicate one end of a pipe to standard output or standard error, you should close both ends of that pipe. It is a common mistake not to have enough calls to close() in multiprocess code using pipes. Occasionally, you get away with being sloppy, but the details vary by case and usually you don't.

Upvotes: 4

Related Questions