Skip to content

Commit 21dce58

Browse files
committed
Handle signals properly on Windows
1 parent c50b628 commit 21dce58

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

examples/main/main.cpp

+6-6
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
#include <signal.h>
2222
#include <unistd.h>
2323
#elif defined (_WIN32)
24+
#define WIN32_LEAN_AND_MEAN
25+
#include <windows.h>
2426
#include <signal.h>
2527
#endif
2628

@@ -215,7 +217,10 @@ int main(int argc, char ** argv) {
215217
sigint_action.sa_flags = 0;
216218
sigaction(SIGINT, &sigint_action, NULL);
217219
#elif defined (_WIN32)
218-
signal(SIGINT, sigint_handler);
220+
auto console_ctrl_handler = [](DWORD ctrl_type) -> BOOL {
221+
return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
222+
};
223+
SetConsoleCtrlHandler(static_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
219224
#endif
220225

221226
fprintf(stderr, "%s: interactive mode on.\n", __func__);
@@ -397,11 +402,6 @@ int main(int argc, char ** argv) {
397402
// potentially set color to indicate we are taking user input
398403
set_console_color(con_st, CONSOLE_COLOR_USER_INPUT);
399404

400-
#if defined (_WIN32)
401-
// Windows: must reactivate sigint handler after each signal
402-
signal(SIGINT, sigint_handler);
403-
#endif
404-
405405
if (params.instruct) {
406406
printf("\n> ");
407407
}

0 commit comments

Comments
 (0)