如何使用signal_set终止boost asio io_service运行

时间:2013-04-25 16:07:55

标签: c++ boost boost-asio

我正在尝试将一个^ C处理程序添加到boost io_service。在添加之前,服务将在I / O耗尽时退出(所有关联的套接字都已关闭)。添加signal_set后,在获得SIGINT之前不会退出。例如:

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

我希望立即退出,而不是等待信号,因为没有I / O要做。与...同义的东西:

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

0 个答案:

没有答案