Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
os: API to detect that the read end of a pipe was closed #26049
Currently there is no API in Go to detect that the read end of a pipe was closed without writing to the pipe a non-empty slice. This prevents, for example, to write in a safe Go a version of GNU tail utility that exits immediately when it detects that the read end of its stdout was closed even when it waits for more input like when it is called via
tail -f file-to-follow | grep -q foo
GNU tail exits immediately after the grep finds the word foo and terminates without waiting that the file-to-follow will be extended and trying to write those extra bytes to stdout.
Yet to write such functionality in Go one needs to use unsafe code to call sys.Select or similar and wait for an syscall.EPIPE from the stdout descriptor.
What version of Go are you using (
changed the title from
API to detect that the read end of a pipe was closed
os: API to detect that the read end of a pipe was closed
Jun 25, 2018
An API that is sufficient to implement that tail-like functionality is to add to os.signal something like
that returns a channel that becomes ready when the read end of the pipe closes. It is very OK if this only works with pipes where SetWriteDeadline works, i.e. the pipes that the poller supports.
Alternatively the API can take a callback that is called when the pipe is closed, i.e. like
The nice thing of this form is that one can pass there CancelFunc from
On systems with kqueue the interface also provides notifications about the closed read end of the pipe. But on Windows it seems with anonymous pipes the only way to support this is via periodic calls to the write function with zero-length buffer. At least the question on StackOverflow has not got a better answer, https://stackoverflow.com/questions/11564166/detecting-if-anonymous-pipe-is-writable-to-detect-when-to-end-process
Almost 50 years on and we still don't understand how to handle a closed pipe. It's remarkable how much energy has been consumed on this topic, how many crashes caused, how many solutions proposed.
I would be more comfortable about this if there was a non-epoll, non-signal-catching way to learn about a closed pipe. Is there?