我的以下程序永远无法到达handler()。我正在使用信号集安装自己的信号处理程序。
void handler( const boost::system::error_code& error , int signal_number )
{
ROS_ERROR("inside signal handler");
exit(1);
}
int main( int argc , char** argv )
{
ros::init(argc, argv, "name", ros::init_options::NoSigintHandler);
boost::asio::io_service io_service;
// Construct a signal set registered for process termination.
boost::asio::signal_set signals(io_service, SIGINT );
// Start an asynchronous wait for one of the signals to occur.
signals.async_wait( handler );
boost::asio::spawn(io_service, {
while(1);
}
);
io_service.run();
return 0;
}
有趣,当我使用
signals.async_wait(
[&ioSservice](boost::system::error_code& code, int signalNo) {
ioService.stop();
});
然后它不会终止。
答案 0 :(得分:4)
您只有一个线程为io_service
提供服务,而while(1);
却很忙,因此无法运行信号处理程序。
io_service
就像一个队列。当您async_wait
处理某件事时,asio会安排要添加的回调队列在它们相关的io_service
中运行。当您调用io_service::run
时,调用线程将从io_service
的队列中提取未决项目并运行它们。
在这种情况下,当您调用io_service.run()
时,队列中正在工作:由spawn
创建的运行循环while
的循环。由于循环永远不会结束,因此主线程永远无法完成运行该作业。稍后,signal_set
收到SIGINT
时,它将另一个作业添加到队列中以调用handler
,但是它将永远不会运行,因为从队列中拉出作业的唯一线程正忙于无休止的while
循环。
处理此问题的方法是避免将长期运行的作业放入io_service
的队列中,并且/或者让多个线程为io_service
提供服务:
void handler(const boost::system::error_code& error, int signal_number)
{
std::cout << "inside signal handler\n";
exit(1);
}
int main(int argc, char** argv)
{
boost::asio::io_service io_service;
// You can use a work object to avoid having the io_service
// stop when its job queue empties.
boost::asio::io_service::work work(io_service);
boost::asio::signal_set signals(io_service, SIGINT);
signals.async_wait(handler);
// Now that there's a work object keeping this io_service running
// this call isn't needed at all. It's just here to demonstrate
// that it works
boost::asio::spawn(io_service, []{
while(1);
}
);
// Start a second thread to run io_service jobs
std::thread t([&io_service]{ io_service.run(); });
// Also handle io_service jobs on this thread
io_service.run();
return 0;
}