如何prevent SIGPIPEs(或妥善处理) [英] How to prevent SIGPIPEs (or handle them properly)
问题描述
我必须能够接受对TCP或本地UNIX套接字连接一个小型服务器程序,读取一个简单的命令,并根据命令,发送一个答复。问题是,客户端可能在答案没有兴趣有时候,早退出,所以写到插座会导致一个SIGPIPE,让我的服务器崩溃。什么是prevent这里崩溃的最佳做法?有没有一种方法来检查,如果该行的另一边是还在读书? (选择()似乎并不在这里工作,因为它总是说,插座是可写的)。或者我应该只是赶上了处理程序SIGPIPE和忽略它?
I have a small server program that accepts connections on a TCP or local UNIX socket, reads a simple command and, depending on the command, sends a reply. The problem is that the client may have no interest in the answer sometimes and exits early, so writing to that socket will cause a SIGPIPE and make my server crash. What's the best practice to prevent the crash here? Is there a way to check if the other side of the line is still reading? (select() doesn't seem to work here as it always says the socket is writable). Or should I just catch the SIGPIPE with a handler and ignore it?
推荐答案
您一般要忽略 SIGPIPE
并在code直接处理错误。这是因为在C信号处理对他们能做什么的限制。
You generally want to ignore the SIGPIPE
and handle the error directly in your code. This is because signal handlers in C have many restrictions on what they can do.
最轻便的方式来做到这一点是设置 SIGPIPE
处理程序 SIG_IGN
。这将prevent从引起 SIGPIPE
信号的任何插座或管道写。
The most portable way to do this is to set the SIGPIPE
handler to SIG_IGN
. This will prevent any socket or pipe write from causing a SIGPIPE
signal.
要忽略 SIGPIPE
信号,请使用以下code:
To ignore the SIGPIPE
signal, use the following code:
signal(SIGPIPE, SIG_IGN);
如果您使用的发送()
通话,另一种选择是使用 MSG_NOSIGNAL
选项,将打开 SIGPIPE
关闭行为在每次呼叫的基础。请注意,并非所有的操作系统都支持 MSG_NOSIGNAL
标记。
If you're using the send()
call, another option is to use the MSG_NOSIGNAL
option, which will turn the SIGPIPE
behavior off on a per call basis. Note that not all operating systems support the MSG_NOSIGNAL
flag.
最后,您可能还需要考虑 SO_SIGNOPIPE
插座标志,可以用设置的setsockopt()
上某些操作系统。这将prevent SIGPIPE
由被写入造成的只是它被设置在插座上。
Lastly, you may also want to consider the SO_SIGNOPIPE
socket flag that can be set with setsockopt()
on some operating systems. This will prevent SIGPIPE
from being caused by writes just to the sockets it is set on.
这篇关于如何prevent SIGPIPEs(或妥善处理)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!