#include #include #include #include #include volatile sig_atomic_t sig_int_flag = 0; volatile sig_atomic_t sig_term_flag = 0; typedef void (*SigHandler)(int); void EstablishSignal(int sig, SigHandler handler) { SigHandler res; res = signal(sig, handler); if(res == SIG_ERR) { perror("Could not establish signal handler"); exit(EXIT_FAILURE); } } void sig_int_handler(int sig) { EstablishSignal(SIGINT, sig_int_handler); assert(sig == SIGINT); printf("Caught SIGINT!\n"); /* Risky - preferably we should not call any library function that is not explicitely marked as reentrant! (the signal may arrive while we are already executing this function) */ sig_int_flag = 1; } void sig_term_handler(int sig) { EstablishSignal(SIGTERM, sig_term_handler); assert(sig == SIGTERM); printf("Caught SIGTERM!\n"); /* Risky! */ sig_term_flag = 1; } int main(int argc, char* argv[]) { int i; int int_counter = 0; EstablishSignal(SIGTERM, sig_term_handler); EstablishSignal(SIGINT, sig_int_handler); for(i=0; i<1000 && !sig_term_flag; i++) { printf("Going to sleep!\n"); sleep(30); if(sig_int_flag) { sig_int_flag = 0; int_counter++; } } printf("SIGINTs: %d Iterations:%d\n", int_counter, i); return EXIT_SUCCESS; }