Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it really necessary to close the unused end of the pipe in a process

Tags:

c

unix

pipe

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

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?

like image 748
kadina Avatar asked Jul 15 '14 18:07

kadina


People also ask

Why do we need to close pipe?

If the writing process doesn't close the read end of the pipe, then even after the other process closes the read end of the pipe, the writing process will fill the pipe, and a further attempt to write will block indefinitely.

What happens if you don't close pipes?

If the parent doesn't close the unused end of the pipe, there will still be two handles for it. If the child dies, the handle on the child side goes away, but there's still the open handle held by the parent -- thus, there will never be a "broken pipe" or "EOF" arriving because the pipe is still perfectly valid.

Do you need to close file descriptors?

Yes, close your file descriptors and free all heap memory, even if you know that the OS will clean it up - that way, when you run valgrind or some similar tool, you don't get a lot of noise in the results, and you can easily recognize "legit" fd leaks.

Which end of pipe is read end?

pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe.


1 Answers

Here's the problem if you don't. In your example, the parent creates a pipe for writing to the child. It then forks the child but does not close its own read descriptor. This means that there are still two read descriptors on the pipe.

If the child had the only one and it closed it (for example, by exiting), the parent would get a SIGPIPE signal or, if that was masked, an error on writing to the pipe.

However, there is a second read descriptor on the pipe (the parent's). Now, if the child exits, the pipe will remain open. The parent can continue to write to the pipe until it fills and then the next write will block (or return without writing if non-blocking).

Thus, by not closing the parent's read descriptor, the parent cannot detect that the child has closed its descriptor.

like image 184
DoxyLover Avatar answered Sep 20 '22 18:09

DoxyLover