Is there a portable way in Golang to detect that os.Stdout that is connected to a pipe to another process was closed on the read end without writing something to it? I am writing a command line helper that should exit if its stdout was closed because, for example, the process connected to the read end of the pipe exited. For example, when run from a shell like:
go run my_helper.go | sleep 1
the helper should exit when the sleep process exits closing the read end of the pipe without waiting for explicit kill signal or an input that triggers eventual non-zero write to stdout.
I though I could just poll stdout periodically writing zero-length slices, but it seems Go optimized zero-length writes and did nothing in such cases. I.e.
n, err := os.Stdout.Write(nil)
returns 0, nil
even if os.Stdout was closed on the read end.
As the code needs to run only on Linux, I can workaround this in principle using syscall.Select
and waiting for write errors on os.Stdout
, but maybe I missed something.