使用boost asio捕获Ctrl-C [英] Using boost asio to Catch Ctrl-C
问题描述
我正在尝试在应用程序中捕获 Ctrl - C ,如以下MWE中所示
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;
}
}
不幸的是,当我按下 Ctrl + C 时,没有调用
handler().相反,循环不再等待用户输入,如下所示:
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:
如果重要的话,我在Windows上,我知道有Windows特定的捕获 Ctrl + C 的方法,但是我想使用boost为方便移植提供了可能.
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
.
boost ASIO in centered on the io_service
object, all the tasks you request (especially the async ones) are usually handled by the io_service
.
这样做:
// Start an asynchronous wait for one of the signals to occur.
signals.async_wait( handler );
您需要服务异步等待信号,并在发生这种情况时调用您的 handler
.
You require the service to wait on the signals asynchronously and call your handler
when it happens.
问题是,您的 io_service
没有运行.
The thing is, your io_service
is not running.
因此,如果您希望它正常工作,则需要启动它:
So if you want it to work correctly you need to start it:
#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 即可完成您的期望.
Then pressing Ctrl + C will do what you expect.
请注意, io_service
基本上会取代无限循环,因此您在其中执行的所有操作都应成为 io_service
的任务.
Note that the io_service
basically replaces your infinite loop, so anything you would have done inside of it should become tasks for the io_service
.
这篇关于使用boost asio捕获Ctrl-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!