If you're read
ing from a regular file, and it returns 0 because you got to EOF, but then someone else appends something to the file, a subsequent read
syscall will give you the new data. Similarly, if you're read
ing from a TTY, and it returns 0 because the user hit Ctrl D, but then the user types some more text, a subsequent read
syscall will give you the new data. But what about if you're read
ing from a pipe? Is it ever possible that one read
syscall could return 0, and that a later one would then get more data out of a pipe?
CodePudding user response:
Yes. read
on the same FD will start returning data again if something reopens the pipe for writing.
You can easily reopen named pipes, and Linux lets you reopen anonymous pipes by writing to /proc/<pid>/fd/<fd>
. In particular, you can open this file for writing even if the FD is only open for reading in the process that you're getting it from.
CodePudding user response:
If you try to read an internal unnamed-pipe and there is no data the reader will stall by default.
If the writer closes the pipe then the reader will return with no data, but now the pipe is closed. Nobody can write. If the writer duplicated, the the reader will stall until all writers are closed (by default).
You can set the pipe mode to O_NONBLOCK via fcntl F_SETFL, but then calling this returns a fail code EAGAIN or EWOULDBLOCK (the same on my linux?) if there is currently no content available.
If the pipe is actually a named-pipe = fifo, i.e. opened as a regular path file that was previously created with mkfifo(), then again the reader just blocks or returns EAGAIN. It will block if there are no writers, or if the writer(s) are just not outputting.
Note that just open()ing fifo for read will block if there are /no/ writers, until there is a writer, even if there is no content written. Internally, it is documented that the pipe is not created until there is at least 1 reader and 1 writer (or O_NONBLOCK). But opening fifo read with O_NONBLOCK always succeeds, so you don't know if there are any writers or not.
So there is no easy documented way for a fifo reader to know if there are no writers. You could perhaps fire a signal at the stalled blocking open-for-read?
I'm not sure what happens if the file is unlinked (deleted) and there are no writers. Perhaps that triggers an EOF? Or perhaps your code will wait for ever, as it is now not possible to add more writers?