boost::asio 无法捕获 SIGINT

boost::asio fails to catch SIGINT

本文关键字:SIGINT asio boost      更新时间:2023-10-16

我的以下程序永远不会到达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();
});

然后它不会终止。

你只有一个线程为你io_service提供服务,并且它忙于while(1);,所以它无法运行信号处理程序。

io_service就像一个队列。 当您async_wait事情时,asio 将安排排队添加回调以运行其关联的io_service。 当你调用io_service::run时,调用线程将从io_service的队列中提取待处理的项目并运行它们。

在这种情况下,当您调用io_service.run()时,队列中有作业:由运行无限while循环的spawn创建的作业。 由于循环永不结束,因此主线程永远无法完成运行该作业。 稍后,当signal_set收到SIGINT时,它会向队列添加另一个作业来调用handler,但它永远不会运行,因为唯一从队列中拉出作业的线程正忙于无休止的while循环。

处理此问题的方法是避免将长时间运行的作业放入io_service的队列中和/或让多个线程为io_service提供服务:

void handler(const boost::system::error_code& error, int signal_number)
{
std::cout << "inside signal handlern";
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;
}