发送()问题
当我使用网络浏览器测试我的程序时,我可以很好地写入套接字/FD,所以我决定循环它并在连接中切断连接,我注意到一个问题。 send() 能够在套接字不可用时关闭整个程序。我认为问题在于该程序陷入了第 22 条军规并自行关闭。所以我将套接字设置为不阻塞。没有变化。对于为什么会发生这种情况有什么想法吗?
else if ( b->temp_socket_list[read].revents & POLLOUT ) {
printf ( "#Write#\n" );
char *done = "Done!";
int sent = send ( sock, done, 5, 0 );
printf ( "end\n", sent );
}
When I test my program using a web browser I can write to the socket/FD just fine so i decided to loop it and cut the connection mid-connection and I noticed a problem. send() is capable of closing down the entire program when the socket is unavailable. I thought the problem was that the program caught itself in a catch-22 and closed itself. So I set the socket to not block. No change. Any ideas of why this is happening?
else if ( b->temp_socket_list[read].revents & POLLOUT ) {
printf ( "#Write#\n" );
char *done = "Done!";
int sent = send ( sock, done, 5, 0 );
printf ( "end\n", sent );
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能是由于
SIGPIPE
信号的默认操作造成的。要忽略此信号,请使用以下内容:然后,套接字错误将被报告为套接字函数的返回值,而不是信号。
This is likely due to the default action of the
SIGPIPE
signal. To ignore this signal, use something like:Socket errors will then be reported as return values from socket functions, rather than a signal.
这是哪个平台?
在 UNIX 上,某些情况下,当连接断开时,您会收到信号 (SIGPIPE),并且默认情况下会终止程序...解决方案是为 SIGPIPE 安装一个不执行任何操作的信号处理程序。
Which platform is this?
On UNIX in some cases you can get a signal when the connection goes down (SIGPIPE) and this terminates the program by default... the solution is to install a signal handler for SIGPIPE that does nothing.
试试这个:
我不是 100% 确定它有效,但我相信它应该有效,如果它是正确的,那么它是一个可以从库代码中使用的解决方案,而不会弄乱调用者或其他可能使用信号的线程的状态。
另请注意,如果程序(甚至只是当前线程)不想使用
SIGPIPE
,您可以通过永久阻止SIGPIPE
来简化这一过程:Try this:
I'm not 100% sure it works, but I believe it should, and if it's correct then it's a solution that can be used from library code without messing up the state of the caller or other potentially-signal-using threads.
Also note that if the program (or even just the current thread) does not want to make use of
SIGPIPE
, you can simplify this a lot by just leavingSIGPIPE
permanently blocked: