SIGPIPE为什么存在? [英] Why does SIGPIPE exist?

查看:107
本文介绍了SIGPIPE为什么存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,SIGPIPE只能作为write()的结果出现,它可以(并且确实)返回-1并将errno设置为EPIPE.信号的开销?每次使用管道时,我都会忽略SIGPIPE,并且从未因此而感到痛苦,我是否缺少任何东西?

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?

推荐答案

我不购买以前接受的答案. SIGPIPE是恰好在write失败且EPIPE失败时生成的,而不是事先生成的-实际上,避免SIGPIPE而不更改全局信号配置的一种安全方法是使用pthread_sigmask暂时屏蔽它,执行write ,然后执行sigtimedwait(超时为零)以消耗任何未决的SIGPIPE信号(发送至调用线程,而不是进程),然后再次对其进行屏蔽.

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.

我相信SIGPIPE存在的原因要简单得多:为连续读取输入,以某种方式对其进行转换并写入输出的纯过滤器"程序建立合理的默认行为.如果没有SIGPIPE,除非这些程序显式处理写错误并立即退出(无论如何,这不是所有写错误的理想行为),否则它们将继续运行,直到它们的输入用尽,即使它们的输出管道已关闭.当然,可以通过显式检查EPIPE并退出来复制SIGPIPE的行为,但是SIGPIPE的全部目的是在程序员懒惰时默认情况下实现此行为.

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.

这篇关于SIGPIPE为什么存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆