Skip to content

Commit db06041

Browse files
committed
Handle signals properly on Windows
1 parent 305eb5a commit db06041

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
@@ -21,6 +21,9 @@
2121
#include <signal.h>
2222
#include <unistd.h>
2323
#elif defined (_WIN32)
24+
#define WIN32_LEAN_AND_MEAN
25+
#define NOMINMAX
26+
#include <windows.h>
2427
#include <signal.h>
2528
#endif
2629

@@ -261,7 +264,10 @@ int main(int argc, char ** argv) {
261264
sigint_action.sa_flags = 0;
262265
sigaction(SIGINT, &sigint_action, NULL);
263266
#elif defined (_WIN32)
264-
signal(SIGINT, sigint_handler);
267+
auto console_ctrl_handler = [](DWORD ctrl_type) -> BOOL {
268+
return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
269+
};
270+
SetConsoleCtrlHandler(static_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
265271
#endif
266272

267273
fprintf(stderr, "%s: interactive mode on.\n", __func__);
@@ -539,11 +545,6 @@ int main(int argc, char ** argv) {
539545
// potentially set color to indicate we are taking user input
540546
set_console_color(con_st, CONSOLE_COLOR_USER_INPUT);
541547

542-
#if defined (_WIN32)
543-
// Windows: must reactivate sigint handler after each signal
544-
signal(SIGINT, sigint_handler);
545-
#endif
546-
547548
if (params.instruct) {
548549
printf("\n> ");
549550
}
@@ -627,10 +628,6 @@ int main(int argc, char ** argv) {
627628
}
628629
}
629630

630-
#if defined (_WIN32)
631-
signal(SIGINT, SIG_DFL);
632-
#endif
633-
634631
llama_print_timings(ctx);
635632
llama_free(ctx);
636633

0 commit comments

Comments
 (0)