【发布时间】:2016-07-18 10:13:24
【问题描述】:
我的程序充当客户端可以连接的服务器。一旦客户端连接,他将每隔约 5 秒从服务器获取更新。这是每 5 秒调用一次以将新数据发送到客户端的 write 函数:
void NIUserSession::write(std::string &message_orig)
{
std::cout << "Writing message" << std::endl;
std::shared_ptr<std::string> message = std::make_shared<std::string>( message_orig );
message->append("<EOF>");
boost::system::error_code ec;
boost::asio::async_write(this->socket_, boost::asio::buffer(*message),
boost::asio::transfer_all(), boost::bind(&NIUserSession::writeHandler,
this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred(),
message
));
}
void NIUserSession::writeHandler(const boost::system::error_code &error, std::size_t bytes_transferred, std::shared_ptr<std::string> message)
{
std::cout << "Write Handler" << std::endl;
if(error)
{
std::cout << "Write handler error: " << error.message() << std::endl;
this->disconnect();
}
}
void NIUserSession::disconnect()
{
std::cout << "Disconnecting client, cancling all write and read operations." << std::endl;
this->socket_.lowest_layer().cancel();
delete this;
}
如果写入操作出错,服务器和客户端之间的连接将关闭,所有异步操作都将被取消 (this->socket_.lowest_layer().cancel();)。
问题是如果连接超时,writeHandler 不会立即被调用。相反,写入操作“堆叠”直到第一个到达writeHandler。
这应该是程序的正常输出:
Writing message
Write Handler
... Other stuff ...
... Other stuff ...
Writing message
Write Handler
如果连接超时,会发生以下情况:
Writing message
Write Handler
Write handler error: Connection timed out
Disconnecting client, cancling all write and read operations.
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Segmentation fault
最后,出现分段错误。我认为这是因为 disconnect 被调用,而其他异步操作仍在进行中。
我以为我可以在第一次异步操作失败后直接使用this->socket_.lowest_layer().cancel(); 来避免它,但它不起作用。
如何避免分段错误?
【问题讨论】:
标签: c++ asynchronous boost segmentation-fault boost-asio