/*------------------------------------------------------------------------ | | File: signal03.c | | Description: This program repeatedly increments a counter. When | overflow occurs, it increments an separate overflow counter. | It has an infinite loop. Typing ctrl-c at the keyboard sends | this process a SIGINT signal. A signal handler, sigint_handler | catches the signal increments a signal counter and prints the | current counts. The signal handler terminates the program when | a maximum number of allowed SIGINT signals have been received. | The user defined sigint_handler function executes instead of | the default handler since sigint_handler is registered as | the handler (the signal function does this). | | | Created: 12 Jan 15 | Author: glancast | +-----------------------------------------------------------------------*/ #include #include #include const int MAXSIGNALS = 5; void sigint_handler(int sig); /** * Counters are now global so that * the signal handler can access them. */ int cnt = 0; int overflow = 0; int signals = 0; int main(int argc, char *argv[]) { printf("This program increments a counter. Type ctrl-c to send a SIGINT signal.\n"); printf("%d maximum number of SIGINT signals allowed.\n", MAXSIGNALS); signal(SIGINT, sigint_handler); while(1) { if (cnt + 1 < cnt) { cnt = 0; overflow++; } else { cnt++; } } return 0; } void sigint_handler(int sig) { signals++; printf("\nsigint %d: overflow = %d, count = %d\n", signals, overflow, cnt); if (signals == MAXSIGNALS) { printf("\nMaximum number of SIGINT signals allowed is %d. Exiting\n", MAXSIGNALS); printf("Edit MAXSIGNALS if you want more!\n\n"); exit(0); } }