Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 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?

See Question&Answers more detail:os

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

1 Answer

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).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...