在不关闭本机处理程序的情况下销毁 Boost Asio 套接字

Destroying Boost Asio socket without closing native handler

我面临以下问题。我正在尝试将第三方库与 boost Asio 一起使用,我需要在 io_service 事件循环中注入该库使用的一些套接字描述符。

我使用的方法是创建一个 boost::asio::ip::tcp::socket 传递我的库提供的本机处理程序。

问题是库只会传达它对特定套接字通知不感兴趣(这意味着库可能会关闭套接字或稍后重新使用它)。无论如何,我想清理升压套接字并销毁它们,但不关闭本机处理程序(即文件描述符)。

简而言之,有没有什么方法可以在不关闭底层处理程序的情况下销毁 boost::asio::ip::tcp::socket?我知道可以改用 posix::stream_descriptor,但我希望我的解决方案是可移植的。

but I would like my solution to be portable

触及本机句柄的那一刻,程序便不再可移植。

但是,一旦您接受了这一点,就可以在本机句柄上调用 dup() [unix] 或 DuplicateHandle() [windows]。

您可以尝试切换到 posix::stream_descriptor 并使用其 release 方法。

没有。如果不关闭本机处理程序,就无法销毁 ip::tcp::socket。这不能移植实现,因此 Asio 不支持它。特别是,在 Windows 8.1 之前,一旦套接字与 I/O 完成端口相关联,则只能通过关闭它来取消关联套接字1。查看 this 相关的 github 问题,其中 Chris Kohlhoff 响应了此功能请求:

This is not supported because it cannot be portably implemented. Specifically, on Windows a socket is associated to an I/O completion port and cannot be disassociated.

If you are only targeting POSIX-based systems then perhaps you can stick the descriptor into a posix::stream_descriptor instead? This class does provide a release() member function.


1. Windows 8.1 启用通过 FileReplaceCompletionInformation 删除完成端口关联而不关闭套接字。