I don’t buy the previously-accepted answer.
SIGPIPE is generated exactly when the
write fails with
EPIPE, not beforehand – in fact one safe way to avoid
SIGPIPE without changing global signal dispositions is to temporarily mask it with
pthread_sigmask, perform the
write, then perform
sigtimedwait (with zero timeout) to consume any pending
SIGPIPE signal (which is sent to the calling thread, not the process) before unmasking it again.
I believe the reason
SIGPIPE exists is much simpler: establishing sane default behavior for pure “filter” programs that continuously read input, transform it somehow, and write output. Without
SIGPIPE, unless these programs explicitly handle write errors and immediately exit (which might not be the desired behavior for all write errors, anyway), they will continue running until they run out of input even if their output pipe has been closed. Sure you can duplicate the behavior of
SIGPIPE by explicitly checking for
EPIPE and exiting, but the whole purpose of
SIGPIPE was to achieve this behavior by default when the programmer is lazy.