What makes a Unix process die with Broken pipe

pipe

Here are some options I thought of, not sure which is the right one.

  1. There was an I/O error reading from the pipe.
  2. The process writing to the other end of the pipe died with a failure.
  3. All processes who could write to the pipe have closed it.
  4. The write buffer of the pipe is full.
  5. The peer has closed the other direction of the duplex pipe.
  6. Writing failed because there are no processes which could read from the pipe.
  7. A system call returned the EPIPE error, and there was no error handler installed.

Best Answer

A process receives a SIGPIPE when it attempts to write to a pipe (named or not) or socket of type SOCK_STREAM that has no reader left.

It's generally wanted behaviour. A typical example is:

find . | head -n 1

You don't want find to keep on running once head has terminated (and then closed the only file descriptor open for reading on that pipe).

The yes command typically relies on that signal to terminate.

yes | some-command

Will write "y" until some-command terminates.

Note that it's not only when commands exit, it's when all the reader have closed their reading fd to the pipe. In:

yes | ( sleep 1; exec <&-; ps -fC yes)
      1 2       1        0

There will be 1 (the subshell), then 2 (subshell + sleep), then 1 (subshell) then 0 fd reading from the pipe after the subshell explicitely closes its stdin, and that's when yes will receive a SIGPIPE.

Above, most shells use a pipe(2) while ksh93 uses a socketpair(2), but the behaviour is the same in that regard.

When a process ignores the SIGPIPE, the writing system call (generally write, but could be pwrite, send, splice...) returns with a EPIPE error. So processes wanting to handle the broken pipe manually would typically ignore SIGPIPE and take action upon a EPIPE error.