Skip to content

Commit 13b0c68

Browse files
Handle signals properly on Windows (#1123)
1 parent 55bc5f0 commit 13b0c68

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed

examples/main/main.cpp

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@
2222
#include <signal.h>
2323
#include <unistd.h>
2424
#elif defined (_WIN32)
25+
#define WIN32_LEAN_AND_MEAN
26+
#define NOMINMAX
27+
#include <windows.h>
2528
#include <signal.h>
2629
#endif
2730

@@ -240,7 +243,10 @@ int main(int argc, char ** argv) {
240243
sigint_action.sa_flags = 0;
241244
sigaction(SIGINT, &sigint_action, NULL);
242245
#elif defined (_WIN32)
243-
signal(SIGINT, sigint_handler);
246+
auto console_ctrl_handler = [](DWORD ctrl_type) -> BOOL {
247+
return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
248+
};
249+
SetConsoleCtrlHandler(static_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
244250
#endif
245251

246252
fprintf(stderr, "%s: interactive mode on.\n", __func__);
@@ -519,11 +525,6 @@ int main(int argc, char ** argv) {
519525
// potentially set color to indicate we are taking user input
520526
set_console_color(con_st, CONSOLE_COLOR_USER_INPUT);
521527

522-
#if defined (_WIN32)
523-
// Windows: must reactivate sigint handler after each signal
524-
signal(SIGINT, sigint_handler);
525-
#endif
526-
527528
if (params.instruct) {
528529
printf("\n> ");
529530
}
@@ -607,10 +608,6 @@ int main(int argc, char ** argv) {
607608
}
608609
}
609610

610-
#if defined (_WIN32)
611-
signal(SIGINT, SIG_DFL);
612-
#endif
613-
614611
llama_print_timings(ctx);
615612
llama_free(ctx);
616613

0 commit comments

Comments
 (0)