boost::asio 无法捕获 SIGINT
boost::asio fails to catch SIGINT
我的以下程序永远不会到达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;
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 提升 ASIO 无法识别计时器对象
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- boost::asio::steady_timer()与sleep()我应该使用哪一个
- boost::asio如何生成多个协同程序,然后加入它们
- 缓慢提升ASIO
- 从 Boost ASIO 获取 epoll 描述符 io_service对象
- 如何在 Boost.Asio 中使用 Zero-copy sendmsg/receive
- C++ Boost::asio串行通信与Arduino无法写入
- 如何使用 Boost Asio 在 Android 上获取我的本地 udp IP 地址?
- 提升 Asio TCP 服务器 处理多个客户端
- boost::asio UDP 广播客户端仅接收"fast"数据包
- 提升 ASIO - io_service 不要等待连接到线程
- 执行时使用 boost::asio::d eadline_timer 时出错
- Boost.Asio/OpenSSL HTTPS GET certificate trouble
- C++ boost::asio::ip::tcp::acceptor 有时不接受连接器?
- boost::asio data owning `ConstBufferSequence`
- 如何替换此示例代码片段中已弃用的handler_type_t或 boost::asio::handler_type?
- 将 boost 序列化对象的 asio::streambuf 表示转换为 Beast 的 DynamicBody req.body()
- boost::asio 无法捕获 SIGINT