Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

posix - Why does SIGPIPE exist?

From my understanding, SIGPIPE can only occur as the result of a write(), which can (and does) return -1 and set errno to EPIPE... So why do we have the extra overhead of a signal? Every time I work with pipes I ignore SIGPIPE and have never felt any pain as a result, am I missing something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...