[英]ZeroMQ: How to handle Ctrl-C on Windows
I wonder how to handle Ctrl-C
issued from the windows console. 我想知道如何处理Windows控制台发出的
Ctrl-C
。
#include <iostream>
#include <zmq.hpp>
#include <windows.h>
BOOL WINAPI consoleHandler( DWORD dwCtrlType ) {
// what to do here?
return TRUE;
}
int main() {
SetConsoleCtrlHandler( consoleHandler, TRUE );
zmq::context_t context( 1 );
zmq::socket_t socket( context, ZMQ_REP );
socket.bind( "tcp://*:5555" );
while ( true ) {
zmq::message_t request;
try {
socket.recv( &request );
}
catch(zmq::error_t& e) {
std::cout << "zmq error" << std::endl;
}
}
}
This installs a handler function that can act upon a CTRL_C_EVENT
coming from the console. 这将安装一个处理程序函数,该函数可以对来自控制台的
CTRL_C_EVENT
。 Currently, it does nothing. 目前,它什么都不做。 As a result, the
revc
call does not fail throwing an exception as described here (in "Error handling") . 结果,
revc
调用不会抛出异常,如此处所述(在“错误处理”中) 。
What I'd like to do is break
ing the loop in the exception handler and letting the RAII features of the C++ binding do the required cleanup when exiting main()
. 我想做的是
break
异常处理程序中的循环,并让C ++绑定的RAII功能在退出main()
时进行所需的清除。
Usually I create a flag or some sort - either a global bool or a kernel Event. 通常,我创建一个标志或某种标志-全局布尔值或内核事件。
Then you loop waiting on this flag to be reset - so in your case, I would create a simple global bool and then loop on it instead of while (true). 然后循环等待此标志被重置-因此,在您的情况下,我将创建一个简单的全局布尔值,然后在其上循环而不是while(true)。
so: 所以:
bool g_shutdown = false;
BOOL WINAPI consoleHandler( DWORD dwCtrlType ) {
g_shutdown = true;
return TRUE;
}
while (!g_shutdown)
{
// do your zmq work
}
Its simple but effective - though this will not kill your program until the zmq work comes round to the while loop check again. 它简单但有效-尽管直到zmq工作再次进入while循环检查之前,这都不会杀死您的程序。 (You can usually do this by shutting down the socket variable)
(通常可以通过关闭套接字变量来执行此操作)
For a more robust (ie quicker to kill, depending on your situation) use a Event, and WaitforMultipleObject call to wait on both this shutdown event and whatever else your program is waiting on (ie that socket's recv call). 为了获得更强大的功能(即,根据情况而定,更快地杀死它),请使用Event和WaitforMultipleObject调用以等待此关闭事件以及程序正在等待的其他任何事件(即该套接字的recv调用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.