Why do I need to close fds when reading and writing to the pipe? Why do I need to close fds when reading and writing to the pipe? multithreading multithreading

Why do I need to close fds when reading and writing to the pipe?


Your pipe is a unidirectional stream - with a file descriptor for each end. It is not necessary to close() either end of the pipe to allow data to pass along it.

if your pipe spans processes (i.e. is created before a fork() and then the parent and child use it to communicate) you can have one write and and one read end. Then it is good practice to close the unwanted ends of the pipe. This will

  • make sure that when the writing end closes the pipe it is seen by the read end. As an example, say the child is the write side, and it dies. If the parent write side has not been closed, then the parent will not get "eof" (zero length read()) from the pipe - because the pipe has a open write-end.
  • make it clear which process is doing the writing and which process is doing the reading on the pipe.

if your pipe spans threads (within the same process), then do not close the unwanted ends of the pipe. This is because the file descriptor is held by the process, and closing it for one thread will close it for all threads, and therefore the pipe will become unusable.

There is nothing stopping you having one process writing continuously to the pipe and the other process reading. If this is a problem you are having then give us more details to help you out.


After performing the fork, all fds are duplicated. Each process has both ends of the pipe open. If you only want to use one end you should close the other (if your process writes, close the read end).

Besides the obvious fact that if you do not close the descriptors the OS will keep extra entries in the open file table, if you do not close the write end of the pipe, the reader will never receive EOF since there is still a way of entering data into the pipe. AFAIK (and IIRC) there is no problem in not closing the read fd in the other process --that is, besides the file being open for no reason.

It is also recommended (as good practice, not that it affects too much) that you close all descriptors before exiting the application (that is, closing the other end of the pipe after the read/write operation is completed in each process)


A pipe won't give you a bidirectionnal channel, neither will it be multicasting. A pipe as only two ends, it does not have one write end and multiple read end.

If you want many readers, then you need as many pipe as you have reader process.