| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- /* sigdemo1.c - shows how a signal handler works.
- * - run this and press Ctrl-C a few times
- * - counts how many times Ctrl-C is pressed and exits after a certain count
- */
- #include <stdio.h>
- #include <signal.h>
- #include <stdlib.h>
- #include <unistd.h>
- int count = 0; // Global variable to keep track of Ctrl-C presses
- int max_count = 16; // The number of times Ctrl-C should be pressed before exiting
- void f(int signum) /* Signal handler */
- {
- printf("OUCH!");
- for (int i = 0; i < count; i++) { // Print the increasing number of exclamation points
- printf("!");
- }
- printf("\n");
- count++; // increment the count
- if (count >= max_count) {
- exit(0); // exit clean after max count is reached
- }
- }
- int main(int argc, char *argv[])
- {
- if (argc == 2) {
- max_count = atoi(argv[1]); // make argv[1] to an integer
- }
- signal( SIGINT, f ); // do f on SIGINT
- // ignore these
- signal( SIGTSTP, SIG_IGN );
- signal( SIGQUIT, SIG_IGN );
- // enter a main loop
- while (1) {
- sleep(1); // slow down the loop
- }
- return 0;
- }
|