When using a pipe for process-process communication, what is the purpose of closing one end of the pipe?
For example: How to send a simple string between two program
The number of file descriptors that can be open at a given time is limited. If you keep opening pipes and not closing them pretty soon you'll run out of FDs and can't open anything anymore: not pipes, not files, not sockets, ...
Another reason why it can be important to close the pipe is when the closing itself has a meaning to the application. For example, a common use of pipes is to send the errno
from a child process to the parent when using fork
and exec
to launch an external program:
fork
to create a child process, closes its writing end, and tries to read from the pipe. exec
to run a different program:
exec
fails, for example because the program does not exist, the child writes errno
to the pipe, and the parent reads it and knows what went wrong, and can tell the user. exec
is successful the pipe is closed without anything being written. The read
function in the parent returns 0 indicating the pipe was closed and knows the program was successfully started.If the parent did not close its writing end of the pipe before trying to read from the pipe this would not work because the read
function would never return when exec
is successful.