How to use signal_set to terminate boost asio io_service run

这一生的挚爱 提交于 2019-12-11 09:03:23

问题


I am trying to add a ^C handler to a boost io_service. Prior to adding, the service would exit when it ran out of I/O (all the associated sockets had closed). After adding the signal_set, it doesn't exit until it gets a SIGINT. For example:

#include <boost/asio.hpp>
int main() {
  boost::asio::io_service io_service;
  boost::asio::signal_set exit_signal_set{io_service, SIGINT};
  exit_signal_set.async_wait
    ([&](boost::system::error_code const&, int) {
      std::cerr << "exiting, sigint" << std::endl;
      io_service.stop();
    });
  io_service.run();
  return 0;
}

Which I'd expect to exit immediately, rather than waiting for a signal, as there is no I/O to be done. Something synonymous to:

#include <poll.h>
#include <signal.h>
#include <stdio.h>

bool do_exit{false};

static void handle_int(int) {
  do_exit = true;
}

int main() {
  signal(SIGINT, handle_int);
  nfds_t nfds{0};
  struct pollfd pollfds[nfds];
  while (true) {
    poll(pollfds, nfds, 0);
    if (do_exit) {
      fprintf(stderr, "exiting, sigint\n");
      break;
    }
    if (nfds == 0) {
      // What I would like to happen.
      fprintf(stderr, "exiting, nothing left to do\n");
      break;
    }
  }
  return 0;
}

来源:https://stackoverflow.com/questions/16219687/how-to-use-signal-set-to-terminate-boost-asio-io-service-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!