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

后端 未结 2 1807
予麋鹿
予麋鹿 2021-01-02 17:32

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

相关标签:
2条回答
  • 2021-01-02 17:53

    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.

    0 讨论(0)
  • 2021-01-02 18:08

    That's the protocol for the blocking file descriptors. The read end of the pipe waits for data. Closing the write end of it signals end-of-stream. That is actually a powerful synchronization concept.

    You can switch the pipe to non-blocking mode, where lack of data is treated as soft error, so you can just check whether there's anything to read. This is very useful when you have more then one file descriptor to read from (like in a server handling multiple clients). That's where IO multiplexing comes in.

    0 讨论(0)
提交回复
热议问题