Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...