Boost:asio捕获信号
asio可以用于捕捉信号
#include <boost/asio.hpp>
#include <iostream>
using namespace boost::asio;
using namespace std;
void signal_handler(boost::asio::signal_set* sig, const boost::system::error_code & err, int signal)
{
static int s_sigNum = 0;
s_sigNum++;
cout<<"recv "<<s_sigNum<<" signal:"<<signal<<endl;
if(s_sigNum == 1)
{
cout<<"register signal again"<<endl;
auto f = bind(signal_handler, sig, std::placeholders::_1, std::placeholders::_2);
sig->async_wait(f);
}
else
{
cout<<"exit"<<endl;
}
}
int main()
{
io_service ios;
boost::asio::signal_set sig(ios, SIGINT);
sig.add(SIGTERM);
auto f = bind(signal_handler, &sig, std::placeholders::_1, std::placeholders::_2);
sig.async_wait(f);
ios.run();
return 0;
}
//g++ -o sig ./sig.cpp
编译运行程序:
$ ./sig
^Crecv 1 signal:2
register signal again
^Crecv 2 signal:2
exit程序可以捕获信号,并且第一次捕获后会再次注册信号的异步处理
第二次捕获信号后,程序退出