boost asio程式優雅的退出 一

來源:互聯網
上載者:User

當程式能夠攔截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被調用才會退出。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.