繁体   English   中英

Boost.Asio:socket :: close不取消aysnc_read_some

[英]Boost.Asio: socket::close not cancelling aysnc_read_some

我有一个执行async_read_some的boost套接字:

socket_.async_read_some(boost::asio::buffer(data_, max_length),
    boost::bind(&Session::handle_read, this,
    boost::asio::placeholders::error,
    boost::asio::placeholders::bytes_transferred));

当我的Session类被删除时, socket_.close() 我认为这将取消async_read_some并调用Session::handle_read并显示错误。

然而,情况并非如此,并且正在查看basic_socket.hpp

/// Close the socket.
/**
* This function is used to close the socket. Any asynchronous send, receive
* or connect operations will be cancelled immediately, and will complete
* with the boost::asio::error::operation_aborted error.
*
* @throws boost::system::system_error Thrown on failure. Note that, even if
* the function indicates an error, the underlying descriptor is closed.
*
* @note For portable behaviour with respect to graceful closure of a
* connected socket, call shutdown() before closing the socket.
*/
void close()

没有提到读取被取消。 所以我的问题是,如何取消读取,以便我可以干净地关闭套接字?

首先,假设io_service仍处于有效状态,它应该在调用下一次runrun_onepollpoll_one调用io_service 取消/关闭不会突然改变在ASIO中调用处理程序的行为。

因此,如果您在删除Session触发此操作,则将具有UB,因为将在已销毁的对象上调用处理程序,因为您已将原始指针传递给它,该指针随后被删除。

我通常使用的技术是将shared_ptr与pimpl模式的变体结合使用。 我通常在共享指针中实现,并将其传递给各种ASIO调用。 当外部接口被破坏时,我在pimpl上调用shutdown方法,这会导致ASIO取消其操作,然后接口重置其共享指针的副本。

一旦ASIO调用存储的处理程序,它将不再具有共享指针的副本,并且销毁将完成。

在我的例子中,调用acceptor->close()只会向排队的accept_asyncsend_async任务发送operation_aborted错误。 我的read_some_async没有收到错误。 我发现调用socket->shutdown(socket_base::shutdown_type::shutdown_both); socket->close(); 将触发错误完成回调。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM