TCP 发送未返回导致进程崩溃
如果 tcp 服务器和客户端已连接,我想确定客户端何时不再连接。我想我可以简单地通过尝试向客户端发送消息来做到这一点,一旦 send() 返回 -1,我就可以拆除套接字。这个实现可以在 Windows 上找到,但是当我尝试在带有 BSD 套接字的 Linux 上执行此操作时,如果客户端不再连接,对服务器端应用程序上的 send() 的调用会导致我的服务器应用程序崩溃。它甚至不返回 -1...只是终止程序。
请解释为什么会发生这种情况。提前致谢!
If a tcp server and client are connected, I'd like to determine when the client is no longer connected. I thought I can simply do this by attempting to send a message to the client and once send() returns with a -1, I can then tear down the socket. This implementation works find on Windows but the minute I try doing this on Linux with BSD sockets, the call to send() on the server side app causes my server app to crash if the client is no longer connected. It doesn't even return a -1...just terminates the program.
Please explain why this is happening. Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是由 SIGPIPE 信号引起的。请参阅
send(2)
:您可以通过在
send()
调用中使用MSG_NOSIGNAL
标志来避免这种情况,或者通过使用signal(SIGPIPE) 忽略
在程序的开头。在这种情况下,SIGPIPE
信号, SIG_IGN)send()
函数将返回 -1 并将errno
设置为EPIPE
。This is caused by the SIGPIPE signal. See
send(2)
:You can avoid this by using the
MSG_NOSIGNAL
flag on thesend()
call, or by ignoring theSIGPIPE
signal withsignal(SIGPIPE, SIG_IGN)
at the beginning of your program. Then thesend()
function will return -1 and seterrno
toEPIPE
in this situation.您需要忽略 SIGPIPE 信号。如果套接字上发生写入错误,您的进程将收到 SIGPIPE,并且该信号的默认行为是终止您的进程。
在 *nix 上编写您通常需要的网络代码:
You need to ignore the SIGPIPE signal. If a write error happens on a socket, your process with get SIGPIPE, and the default behavior of that signal is to kill your process.
Writing networking code on *nix you usually want: