Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

c - Why should you close a pipe in linux?

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 programs using pipes?

Notice that one side of the pipe is closed in the child and parent processes. Why is this required?

question from:https://stackoverflow.com/questions/19265191/why-should-you-close-a-pipe-in-linux

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you connect two processes - parent and child - using a pipe, you create the pipe before the fork.

The fork makes the both processes have access to both ends of the pipe. This is not desirable.

The reading side is supposed to learn that the writer has finished if it notices an EOF condition. This can only happen if all writing sides are closed. So it is best if it closes its writing FD ASAP.

The writer should close its reading FD just in order not to have too many FDs open and thus reaching a maybe existing limit of open FDs. Besides, if the then only reader dies, the writer gets notified about this by getting a SIGPIPE or at least an EPIPE error (depending on how signals are defined). If there are several readers, the writer cannot detect that "the real one" went away, goes on writing and gets stuck as the writing FD blocks in the hope, the "unused" reader will read something.

So here in detail what happens:

  • parent process calls pipe() and gets 2 file descriptors: let's call it rd and wr.
  • parent process calls fork(). Now both processes have a rd and a wr.
  • Suppose the child process is supposed to be the reader.

    Then

    • the parent should close its reading end (for not wasting FDs and for proper detection of dying reader) and
    • the child must close its writing end (in order to be possible to detect the EOF condition).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...