user3165121
user3165121

Reputation: 51

what happens if we do not close the used end in pipe: Linux/C

Suppose we have a pipe and the parent is writing on it and child is reading from the pipe. We know that the parent should close the reading end BEFORE writing and child should close the writing end BEFORE reading. But I want to know : Is it mandatory to close the writing end after the parent is done with writing? and likewise, the child needs to close the reading end AFTER it is done with reading? if it is mandatory, why so?

Upvotes: 2

Views: 2001

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60068

It's not mandatory, but you probably want to do it, especially on the writing-end of your pipe.

Pipe-end filedescriptors are counted references to pipe-end entities behind them. When you dup a pipe-end filedescriptor or when you fork a process with an open pipe-end, new references to the same pipe-end entity are created and the reference count increases (and each close decreases it).

For the closing of a writing end to turn into an EOF on the other end (usually desirable or else the consumer (reading end) won't know when to stop reading), that writing-end filedescriptor needs to be the last reference to the writing-end entity—a pipe's writing end is only considered closed if all references (filedescriptors) to that writing-end entity are closed.

(This behavior applies to all filedescriptors and isn't limited to pipe-end filedescriptors.)

Upvotes: 3

Related Questions