boost asio程序优雅的退出 一

分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

               

当程序能够拦截kill进程的信号,然后清理资源再退出进程时,就是优雅的退出。boost的asio提供了这个机制。下面用最少的代码演示了这个功能:

#include <cstdlib>#include <boost/asio.hpp>#include <boost/bind.hpp>#include <iostream>using namespace boost;using namespace boost::asio;using namespace std;io_service s;void handle_stop() {    cout << "x" << endl;    s.stop();}int main(int argc, char** argv) {        // The signal_set is used to register for process termination notifications.    boost::asio::signal_set signals(s);        signals.add(SIGINT);    signals.add(SIGTERM);#if defined(SIGQUIT)    signals.add(SIGQUIT);#endif    signals.async_wait(boost::bind(&handle_stop));        s.run();    return 0;}

先定义了全局变量io_service s, 然后基于这个构造一个信号量集合signals.

再添加拦截的信号,然后进入注册异步等待函数handle_stop。

该函数负责关闭io_service。


最后调用io_service::run函数进入等待。run函数直到stop被调用才会退出。



           

分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/fduffyyg/article/details/87895222