如何知道远程端是否使用send系统调用关闭了套接字?

发布于 2024-12-05 04:11:11 字数 130 浏览 6 评论 0原文

即使远程端关闭了连接,send() 系统调用第一次也会成功。 如果我再次发送,则会生成 sigpipe。 我不想使用recv系统调用来知道远程端是否关闭了连接。

那么有人可以告诉我如何仅使用发送系统调用来检测远程端是否关闭了连接?

the send() system call succeeds for the first time even if the remote end closed the connection.
If i send again, then sigpipe will be generated.
I don't want to use recv system call to know whether remote end closed the connection.

So can someone tell me how can i detect whether the remote end closed the connection using only send system call ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

就像说晚安 2024-12-12 04:11:11

您应该做的第一件事是调用 signal(SIGPIPE, SIG_IGN); 以避免在 send() 上接收 SIGPIPE ,或者在 Linux 上,通过MSG_NOSIGNAL 标记为 send()。完成此操作后,当对等方断开连接时,send() 将不会生成 SIGPIPE 信号,而是返回 -1 且 errno == EPIPE

发送 SIGPIPEwrite() 函数的历史行为。 http://pubs.opengroup.org/onlinepubs/009604599/functions/write.html

EPIPE 尝试写入未打开供任何进程读取或仅一端打开的管道或 FIFO。还应将 SIGPIPE 信号发送到线程。

最初它是为 shell 管道创建的(如 cmd | other_cmd)。当在 shell 管道执行期间按下 ctrl-c 时,只有管道中的最后一个进程收到 SIGINT 并终止。要终止管道中的其他进程,SIGPIPE 会被发送到尝试 write() 写入 STDOUT 且其读取器已终止的进程。

The first thing you should do is call signal(SIGPIPE, SIG_IGN); to avoid receiving SIGPIPE on send() or, on Linux, pass MSG_NOSIGNAL flag to send(). Having done that, send() will not generate SIGPIPE signal when a peer has disconnected, but rather return -1 with errno == EPIPE.

Sending SIGPIPE is historical behaviour of write() function. http://pubs.opengroup.org/onlinepubs/009604599/functions/write.html

EPIPE An attempt is made to write to a pipe or FIFO that is not open for reading by any process, or that only has one end open. A SIGPIPE signal shall also be sent to the thread.

Originally it was created for shell pipes (like cmd | other_cmd). When ctrl-c is pressed during shell pipe execution only the last process in the pipe receives SIGINT and terminates. To terminate other processes in the pipe SIGPIPE is sent to the process trying to write() into STDOUT whose reader has already terminated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文