c ++ linux accept()在套接字关闭后阻塞 [英] c++ linux accept() blocking after socket closed

查看:1448
本文介绍了c ++ linux accept()在套接字关闭后阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个侦听新连接的线程

I have a thread that listens for new connections

new_fd = accept(Listen_fd, (struct sockaddr *) & their_addr, &sin_size);

和另一个关闭Listen_fd的线程。在Listen_fd关闭后,它仍然会阻塞。当我使用GDB来尝试和调试accept()不阻塞。我认为这可能是一个问题与SO_LINGER,但它不应该是默认情况下,并且不应该改变时使用GDB。

and another thread that closes Listen_fd when when it's time to close the program. After Listen_fd is closed however, it still blocks. When I use GDB to try and debug accept() doesn't block. I thought that it could be a problem with SO_LINGER, but it shouldn't be on by default, and shouldn't change when using GDB. Any idea whats going on, or any other suggestion to closing the listing socket?

推荐答案

的行为是什么意思? accept 当调用的东西不是一个有效的套接字FD是未定义的。 不是有效的套接字FD包括曾经是有效套接字但已关闭的数字。你可能会说但Borealid,它应该返回EINVAL!,但这不能保证 - 例如,相同的FD号可能会重新分配到一个不同的套接字 close 接受调用。

The behavior of accept when called on something which is not a valid socket FD is undefined. "Not a valid socket FD" includes numbers which were once valid sockets but have since been closed. You might say "but Borealid, it's supposed to return EINVAL!", but that's not guaranteed - for instance, the same FD number might be reassigned to a different socket between your close and accept calls.

因此,即使你孤立和纠正任何使你的程序失败,仍然在未来再次失败。不要这样做 - 更正导致您尝试在关闭的套接字上接受连接的错误。

So, even if you were to isolate and correct whatever makes your program fail, you could still begin to fail again in the future. Don't do it - correct the error that causes you to attempt to accept a connection on a closed socket.

如果您的意图是关闭后 接受 c> 继续 ,那么你应该做的是向 accept 中阻塞的线程发送一个信号。这将给它EINTR它可以干净地脱开 - 然后然后关闭套接字。不要使用它以外的线程关闭它。

If you meant that a call which was previously made to accept continues blocking after close, then what you should do is send a signal to the thread which is blocked in accept. This will give it EINTR and it can cleanly disengage - and then close the socket. Don't close it from a thread other than the one using it.

这篇关于c ++ linux accept()在套接字关闭后阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆