Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the read end of a pipe read EOF only if the write end is closed?

Tags:

c

unix

pipe

I don't really understand the difference between "closing the write end of the pipe" and "not writing anything to the pipe". If I don't write anything to the pipe and the pipe is empty, why is the read end simply blocked rather than reading an EOF? How is that different from closing the write end?

like image 756
Xufeng Avatar asked Mar 05 '14 22:03

Xufeng


People also ask

Which end of a pipe is the read end?

pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe.

When we try to write into pipe whose read end is closed?

When a user process attempts to read from an empty pipe (or FIFO), the following happens: If one end of the pipe is closed, 0 is returned, indicating the end of the file. If the write side of the FIFO has closed, read(2) returns 0 to indicate the end of the file.

Does Close Send EOF?

Until every FD referring to the write end of a pipe is closed, it won't return EOF.

What is the purpose of closing the ends of pipes?

If the reading process doesn't close the write end of the pipe, then after the other process closes its write descriptor, the reader won't see end-of-file, even after it has read all data from the pipe.


1 Answers

Reading an EOF from a pipe (or from anything) indicates that there's no more input, and that there won't be any more input in the future.

If there's no input available at the moment, but the pipe hasn't been closed, then the reader will (by default) block waiting for input; if the writer then writes to the pipe, that data will become available to the reader. An EOF would tell the reader to stop trying to read any more data.

like image 60
Keith Thompson Avatar answered Sep 27 '22 18:09

Keith Thompson