管道损坏时的发送行为
在编写一个简单的服务器客户端应用程序时,我想到了这个问题。当有人尝试写入损坏的管道时,会生成 SIGPIPE。假设我在代码中处理信号。
现在 write 调用返回什么错误 - EPIPE 或 EINTR (因为它被信号中断)。我尝试了一个示例程序,似乎总是得到 EPIPE。这是有保证的行为还是可能是两个错误值中的任何一个?
While writing a simple server-client application, this question came in my mind. When someone tries to write to a broken pipe, a SIGPIPE would be generated. Let's say I handle the signal in my code.
Now what error does the write call returns - EPIPE or EINTR ( as it was interrupted by a signal). I tried with a sample program and I seem to be getting EPIPE always. Is this a guaranteed behavior or it could be any of the two error values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
POSIX 规定应返回 EPIPE 并发送 SIGPIPE:
您可以在此处查看 POSIX 标准
POSIX says that EPIPE should be returned and SIGPIPE sent:
You can have a look at the POSIX standard here
write(2)
调用返回- 1
错误,所以我猜您是在询问errno 的值(3)
。如果您处理、阻止或忽略信号,您将获得
EPIPE
。否则进程默认终止,参见signal(7)
。The
write(2)
call returns-1
on error, so I guess you are asking about the value oferrno(3)
.You'll get
EPIPE
if you handle, block, or ignore the signal. Otherwise the process is terminated by default, seesignal(7)
.一般来说,“被信号中断”(EINTR)是指完全荒谬的 Unix System V 信号处理,如果您的进程在系统调用期间接收(并处理)信号,任何系统调用都可能失败。这需要用
do ... while (ret==-1 && errno==EINTR); 或类似的方法包装每个系统调用。虽然 POSIX 仍然允许这种行为或良好的(“BSD”)行为,但像 GNU/Linux 这样的健全系统默认情况下具有 BSD 行为。您始终可以通过使用正确的参数调用 sigaction 来获取 BSD 行为,甚至可以创建一个包装函数来为您执行此操作。
因此,EINTR 与写入错误引起的 SIGPIPE 无关。
In general, "interrupted by a signal" (EINTR) refers to the utterly ridiculous Unix System V signal handling, whereby ANY system call could fail if your process received (and handled) a signal during the system call. This required wrapping every system call with
do ... while (ret==-1 && errno==EINTR);
or similar. While POSIX still allows either this or the good ("BSD") behavior, sane systems like GNU/Linux have the BSD behavior by default. You can always obtain the BSD behavior by callingsigaction
with the right arguments, or even make a wrapper function to do so for you.As such, EINTR is unrelated to the SIGPIPE caused by write errors.