使用boost asio来捕获Ctrl-C

时间:2017-02-20 10:37:58

标签: c++ boost signals boost-asio

我正在尝试在应用程序中捕获Ctrl-C,如以下MWE中所示

#include <boost/asio/signal_set.hpp>
#include <iostream>

void handler( const boost::system::error_code& error , int signal_number )
{
    std::cout << "handling signal " << signal_number << std::endl;
}

int main( int argc , char** argv )
{
    boost::asio::io_service io_service;

    // Construct a signal set registered for process termination.
    boost::asio::signal_set signals(io_service, SIGINT );

    // Start an asynchronous wait for one of the signals to occur.
    signals.async_wait( handler );

    char choice;
    while( true )
    {
        std::cout << "Press a key: " << std::endl;
        std::cin >> choice; 
    }
}

当我按 Ctrl + C 时,不会调用handler()。相反,循环不再等待用户输入,如下所示:

c:\tmp>CtrlC.exe
Press a key:
d
Press a key:
e
Press a key:
Press a key:
Press a key:
Press a key:
Press a key:
Press a key:
Press a key:
Press a key:
Press a key:

如果重要的话,我在Windows上,我知道有一种Windows特定方式可以捕获 Ctrl + C 但是我想使用boost if可以方便移植。

2 个答案:

答案 0 :(得分:4)

io_service对象为中心提升ASIO,您请求的所有任务(尤其是异步任务)通常由io_service处理。

通过做:

// Start an asynchronous wait for one of the signals to occur.
signals.async_wait( handler );

您需要服务以异步方式等待信号,并在发生时调用handler

问题是,您的io_service未运行。

因此,如果您希望它正常工作,您需要启动它:

#include <boost/asio/signal_set.hpp>
#include <iostream>

void handler( const boost::system::error_code& error , int signal_number )
{
  std::cout << "handling signal " << signal_number << std::endl;
  exit(1);
}

int main( int argc , char** argv )
{
  boost::asio::io_service io_service;

  // Construct a signal set registered for process termination.
  boost::asio::signal_set signals(io_service, SIGINT );

  // Start an asynchronous wait for one of the signals to occur.
  signals.async_wait( handler );

  io_service.run();
}

然后按Ctrl + C将完成您的预期。

请注意,io_service基本上取代了您的无限循环,因此您在其中所做的任何事情都应该成为io_service的任务。

答案 1 :(得分:2)

您需要让io_service执行已传递给它的处理程序。只有当您调用io_servicerun方法时,run_one才能拒绝。您可以在while循环中使用run_one方法:

#include <boost/asio/signal_set.hpp>
#include <iostream>
#include <cstdlib>
#include <limits>

void handler( const boost::system::error_code& error , int signal_number )
{
    // Not safe to use stream here...
    std::cout << "handling signal " << signal_number << std::endl;
    exit (1);
}

int main( int argc , char** argv )
{
    boost::asio::io_service io_service;

    // Construct a signal set registered for process termination.
    boost::asio::signal_set signals(io_service, SIGINT );

    // Start an asynchronous wait for one of the signals to occur.
    signals.async_wait( handler );

    char choice;
    while( true )
    {
        std::cout << "Press a key: " << std::endl;
        std::cin >> choice;
        io_service.run_one();
    }
}