I'm trying to catch the Ctrl-C in application as demonstrated in the following 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;
}
}
Unfortunately handler()
is not called when I press Ctrl+C. On the contrary the loop no longer waits for user input as shown below:
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:
If it matters, I'm on Windows and I know that there is a Windows specific way to catch Ctrl+C but I'd like to use boost if possible for ease of porting.
增强 ASIO 的核心io_service
对象,您请求的所有任务(尤其是异步任务)通常由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();
}
Then pressing Ctrl + C will do what you expect.
请注意,io_service
基本上取代了无限循环,因此您在其中所做的任何事情都应该成为io_service
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)