Saturday, November 14, 2009

Controlling Ctrl^C for quiting program, C programing

If you want Ctrl^C, not to jump out of program right away and give you a chance to save stuffs and get a backup here is the C code for it :

#include
#include
#include


void exit_program(int sig) {
printf("Wake up call ... !!! - Catched signal: %d ... !!\n", sig);
/* DO YOUR STUFFS BEFOR QUITING, if you dont want to wait for the 2nd
Ctrl^C from user you can just have the next commented line :*/
//exit(0);
(void) signal(SIGINT, SIG_DFL);//You need 2nd Ctrl^C to quit
}

int main(void) {
(void) signal(SIGINT, exit_program);
/* waits to read your signal(first Ctrl^C) while running rest of your code, on
Ctrl^C pressed will jump to exit_program method*/

while(1)
printf("I wanna catch Ctrl + C\n"), sleep(1);

return 0;
}

No comments: