From 163bd4955c3b86fa2fa5f89b010412f2e71260eb Mon Sep 17 00:00:00 2001 From: Preston Pan Date: Mon, 6 Feb 2023 00:36:30 -0800 Subject: add interrupt handler --- snake.c | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/snake.c b/snake.c index 6714f63..dc64d0a 100644 --- a/snake.c +++ b/snake.c @@ -2,10 +2,19 @@ #include #include #include +#include /* handling ctrl-c */ #include "vector.h" #include "snake.h" #include "conio.h" +volatile sig_atomic_t INT_CTRL_C = 0; + +/* Unsafe functions like printf cannot be called in async + * interrupt handler */ +void interrupt_handler(int sig) { + INT_CTRL_C = 1; +} + const int boardSize = 12; const int updateInterval = 300000000L; vectorp_t snakePositions; @@ -13,8 +22,12 @@ vector_t foodPos; vector_t lastMoveDir; int main(int argc, char **argv) { + printf("\e[?25l"); /* hide cursor */ + + /* Make a new thread handling interrupts */ + signal(SIGINT, interrupt_handler); + //init values - printf("\e[?25l"); snakePositions = init_vectorp(malloc(5 * sizeof(vector_t)), 5); snakePositions.vectors[0] = init_vector(5, 5); snakePositions.vectors[1] = init_vector(5, 4); @@ -38,6 +51,12 @@ int main(int argc, char **argv) { pthread_create(&listenerID, NULL, get_dir_loop, &threadArg); //main game logic loop while(1) { + /* handle ctrl-c interrupt */ + if (INT_CTRL_C) { + printf("\e[?25h"); + exit(0); + } + //first, draw the current state of the board draw_board(); //handle player input -- cgit v1.3.1