在linux中,调用socket.close后,socket.read_some需要相当长的时间才能返回
我使用 Boost.Asio 作为一个简单的套接字库。
当我打开一个套接字时,我创建一个线程,该线程不断读取该套接字,并在套接字关闭或发生其他错误时返回。
while((read = socket->read_some(buf, ec)) != 0) {
// deal with bytes read
}
此代码在 Windows 和 Mac 上运行良好。然而,在 Linux 中,当套接字从主线程关闭时,socket::read_some
需要相当长的时间才能返回 - 我发现它超过 2 分钟。
我可以做些什么来改善这一点吗?
I'm using Boost.Asio as a simple socket library.
When I open a socket, I create a thread which keeps reading on that socket, and returns when the socket has been closed, or some other errors occured.
while((read = socket->read_some(buf, ec)) != 0) {
// deal with bytes read
}
This code works well on Windows and Mac. However with linux, when the socket is closed from the main thread, it takes quite long time for socket::read_some
to return - I found it's more than 2 minutes.
Is there anything I can do to improve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望取消功能,使用异步套接字。不要使用同步方法,例如
read_some
。这已经在 asio-users 邮件列表上进行了无限的讨论。 boost bug 跟踪器上还有一个 ticket 对此进行了讨论。另请参阅我对类似问题的回答。
If you desire cancel-ability, use asynchronous sockets. Don't use synchronous methods such as
read_some
. This has been discussed ad infinitum on the asio-users mailing list. There's also a ticket on the boost bug tracker discussing it.Also see my answer to a similar question.
最后我找到了原因:在Linux中,如果您使用socket::close关闭套接字,则套接字未关闭。您必须优雅地关闭套接字才能成功关闭它强>。
Finally I found the reason: in Linux if you close a socket with socket::close, the socket is not closed. You must close a socket gracefully to close it successfully.