I'm trying to get my program to exit when ctrl-c is pressed or the window close button is activated, but before the program exits, it needs to run a function. In the original program, it's a function to save a bookmark, so the user can just quit, and the position will be saved.
It works, but with one problem: it needs additional mouse or keyboard input to get past the ch function and exit the loop. I would like the program to just exit without the need for further interaction.
Is there away to do this?
exitnow.c:
Code:
#include <ncurses.h>
#include <assert.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/wait.h>
// gcc exitnow.c -o exitnow -lncursesw && ./exitnow
static bool shutdownNow = false;
void handler(int num) {
write(STDOUT_FILENO, "\n\rCall to exit. Bye.", 20);
shutdownNow = true;
}
void IneedToBeCalledOnExit(int i) {
printf("\nThanks. Did my last task.\n");
}
int main (int argc, char* argv[]){
signal(SIGINT, handler);
signal(SIGKILL, handler);
signal(SIGTERM, handler);
MEVENT event;
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
clear();
cbreak();
mousemask(ALL_MOUSE_EVENTS | REPORT_MOUSE_POSITION, NULL);
mouseinterval(0);
int ch, i = 0;
do {
mvprintw(0,0, "Blah, blah. Stuff happening here: %i\nPress ctrl-c to exit", i);
i++;
ch = getch(); // We're stuck here
} while (shutdownNow == false);
refresh();
endwin();
// RUN ME BEFORE YOU EXIT!
IneedToBeCalledOnExit(i);
return 0;
}
Any ideas?