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

I read about pipes on UNIX for interprocess communication between two processes. I have the following question

Is it really necessary to close the unused end of the pipe? for example, if my parent process writes data to the channel and the child reads from the channel, is it really necessary to close the end of reading in the parent process and close the end of the recording from the child process? Are there any side effects if I do not close these goals? Why do we close these goals?

+8
c unix pipe
source share
4 answers

Here's the problem if you don't. In your example, the parent creates a recording channel for the child. He then expands the child, but does not close his own read handle. This means that the pipe still has two read descriptors.

If the child had one, and he closed it (for example, when exiting), the parent will receive a SIGPIPE signal or, if it was masked, an error occurred while writing to the channel.

However, there is a second read descriptor on the pipe (parent). Now, if the baby comes out, the pipe will remain open. The parent can continue to write to the channel until it is full, and then the next record will be blocked (or return without a record if it is not blocked).

Thus, without closing the parent read descriptor, the parent cannot detect that the child has closed its descriptor.

+12
source share

According to the manual page for getdtablesize

Each process has a fixed-size descriptor table, which is guaranteed to have at least 20 slots.

Each pipe uses two entries in the descriptor table. Closing the unused end of the pipe frees one of these descriptors. Thus, if you were unsuccessful enough to be in a system where each process is limited to 20 descriptors, you would be very motivated to free unnecessary file descriptors.

+3
source share

Pipes are intended for use as unidirectional communication channels. Closing them is a good practice to avoid messing up messages. The Writer descriptor must be closed for reading and vice versa.

+1
source share

Contact here

Quoting from above link:

[...] Each pipe provides one-way communication; information flows from one process to another.

For this reason, the parent and child processes must close the unused end of the channel.

In fact, there is another more important reason for closing unused pipe ends.

Reading a process from pipeline blocks when executing a read system call, unless:

  1. The channel contains enough data to fill the reader buffer or,
  2. The end of file character is sent. The end-of-file character is sent through the channel when each file descriptor is closed to record the end of the channel. Any process reading from the channel and forgetting to close the end of the channel record will never be notified of the "end of file" [...]
0
source share

All Articles