gpt4 book ai didi

TCP 发送不返回导致进程崩溃

转载 作者:可可西里 更新时间:2023-11-01 02:30:47 25 4
gpt4 key购买 nike

如果一个tcp服务器和客户端连接,我想确定客户端什么时候不再连接。我想我可以通过尝试向客户端发送消息来简单地做到这一点,一旦 send() 返回 -1,我就可以拆除套接字。此实现在 Windows 上有效,但当我尝试在使用 BSD 套接字的 Linux 上执行此操作时,如果客户端不再连接,则在服务器端应用程序上调用 send() 会导致我的服务器应用程序崩溃。它甚至不返回 -1...只是终止程序。

请解释为什么会这样。提前致谢!

最佳答案

这是SIGPIPE信号引起的。参见 send(2) :

The send() function shall fail if:
[EPIPE] The socket is shut down for writing, or the socket is connection-mode and is no longer connected. In the latter case, and if the socket is of type SOCK_STREAM or SOCK_SEQPACKET and the MSG_NOSIGNAL flag is not set, the SIGPIPE signal is generated to the calling thread.

您可以通过在 send() 调用上使用 MSG_NOSIGNAL 标志,或者通过使用 忽略 SIGPIPE 信号来避免这种情况signal(SIGPIPE, SIG_IGN) 在程序的开头。在这种情况下,send() 函数将返回 -1 并将 errno 设置为 EPIPE

关于TCP 发送不返回导致进程崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1330397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com