Why should you close a pipe in linux?

后端 未结 3 600
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 12:47

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

3条回答
  •  一生所求
    2020-12-04 13:00

    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:

    1. The parent creates the pipe, calls fork to create a child process, closes its writing end, and tries to read from the pipe.
    2. The child process attempts to use exec to run a different program:
      1. If 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.
      2. If 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.

提交回复
热议问题