How to use signal_set to terminate boost asio io_s

2019-08-03 23:17发布

问题:

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;
}