我正在开发一个使用 boost::asio 在不同端口上侦听 TCP 和 UDP 数据包的应用程序。我通过使用与 asio 教程示例中类似的服务器类来做到这一点,并将它们全部指向一个 io_service。
所以总的来说我的主要功能(win32控制台应用程序)看起来像这样:
int main(int argc, char* argv[])
{
//some initializations here
try
{
asio::io_service io_service;
TcpServer ServerTCP_1(io_service, /*port number here*/);
TcpServer ServerTCP_2(io_service, /*port number here*/);
UdpServer ServerUDP(io_service, /*port number here*/);
io_service.run();
}
catch(std::exception& e)
{
std::cerr << e.what() << std::endl;
}
//cleanup code here
return 0;
}
我还阅读了 HTTP 服务器示例,其中 asignal_set
用于执行异步操作,该操作在退出信号进来时被激活(我也在服务器类中实现了该操作)。
这是我的TcpServer
课:
class TcpServer : private noncopyable
{
public:
TcpServer(asio::io_service& io_service, int port) :
acceptor_(io_service, tcp::endpoint(tcp::v4(), port)),
signals_(io_service), context_(asio::ssl::context::sslv3)
{
SSL_CTX_set_cipher_list(context_.native_handle(), "ALL");
SSL_CTX_set_options(context_.native_handle(), SSL_OP_ALL);
SSL_CTX_use_certificate_ASN1(context_.native_handle(), sizeof(SSL_CERT_X509), SSL_CERT_X509);
SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_RSA, context_.native_handle(), SSL_CERT_RSA, sizeof(SSL_CERT_RSA));
SSL_CTX_set_verify_depth(context_.native_handle(), 1);
signals_.add(SIGINT);
signals_.add(SIGTERM);
signals_.add(SIGBREAK);
#if defined(SIGQUIT)
signals_.add(SIGQUIT);
#endif // defined(SIGQUIT)
signals_.async_wait(boost::bind(&TcpServer::handle_stop, this));
start_accept();
}
private:
tcp::acceptor acceptor_;
asio::ssl::context context_;
asio::signal_set signals_;
TcpConnection::pointer new_ssl_connection;
void start_accept(){
new_ssl_connection.reset(new TcpConnection(acceptor_.get_io_service(), context_));
acceptor_.async_accept( new_ssl_connection->socket(),
boost::bind(&TcpServer::handle_acceptSSL, this, asio::placeholders::error));
}
void handle_acceptSSL(const system::error_code& error){
if(!error)
new_ssl_connection->start();
start_accept();
}
void handle_stop(){
acceptor_.close();
printf("acceptor closed");
}
};
现在,由于我有 3 个不同的服务器对象,他应该关闭它们的所有接受者,留下io_service
没有工作,这再次导致io_service
从调用返回,run()
这应该使程序进入主函数中的清理代码,对吗?除此之外,printf
调用也应该执行 3 次,或者?
好吧,首先io_service
没有返回,清理代码永远不会到达。其次,控制台中最多只显示一个 printf 调用。
第三,通过进行一些调试,我发现当我退出程序时,它handle_stop()
会被调用一次,但由于某种原因,程序会在句柄中的某个位置关闭(这意味着有时他会进入 printf 并在此之后关闭,有时他只是得到到acceptor_.close()
)
另一件可能值得一提的是程序在关闭后不会返回 0 而是返回 0(线程数不同):
The thread 'Win32 Thread' (0x1758) has exited with code 2 (0x2).
The thread 'Win32 Thread' (0x17e8) has exited with code -1073741510 (0xc000013a).
The thread 'Win32 Thread' (0x1034) has exited with code -1073741510 (0xc000013a).
The program '[5924] Server.exe: Native' has exited with code -1073741510 (0xc000013a).
所以我想知道为什么会发生这种情况,如何修复它以及如何正确获取清理代码?