To catch a signal, a signal handler is required. It must be installed properly using function signal() discussed in the previous page.
The following shows a list of important things for installing a signal handler:
#include <stdio.h> #include <signal.h> void INThandler(int); void main(void) { signal(SIGINT, INThandler); while (1) pause(); } void INThandler(int sig) { char c; signal(sig, SIG_IGN); printf("OUCH, did you hit Ctrl-C?\n" "Do you really want to quit? [y/n] "); c = getchar(); if (c == 'y' || c == 'Y') exit(0); else signal(SIGINT, INThandler); }
Then, INThandler() prints a message which asks if the user wants to continue. If the user input is a y or Y, INThandler() exits. Otherwise, it reinstalls itself as the SIGINT handler.
Note that all SIGINT occurs between these two signal() calls cannot be caught.
The following is another simple example. Click here to download this program.
#include <stdio.h> #include <signal.h> unsigned long counter; int MAX; int ALARMcount; int SECOND; void ALARMhandler(int sig) { signal(SIGALRM, SIG_IGN); ALARMcount++; printf("*** ALARMhandler --> alarm received no. %d.\n", ALARMcount); printf("*** ALARMhandler --> counter = %ld\n", counter); printf("*** ALARMhandler --> alarm reset to %d seconds\n", SECOND); if (ALARMcount == MAX) { printf("*** ALARMhandler --> Maximum alarm count reached. exit\n"); exit(0); } counter = 0; /* otherwise, reset counter */ alarm(SECOND); /* set alarm for next run */ signal(SIGALRM, ALARMhandler); /* reinstall the handler */ } void main(int argc, char *argv[]) { if (argc != 3) { printf("Use: %s seconds max-alarm-count\n", argv[0]); printf("No. of seconds is set to 1\n"); SECOND = 1; printf("Max number of alarms set to 5\n"); MAX = 5; } else { SECOND = atoi(argv[1]); MAX = atoi(argv[2]); } counter = 0; ALARMcount = 0; signal(SIGALRM,ALARMhandler); printf("Alarm set to %d seconds and is ticking now.....\n", SECOND); alarm(SECOND); while (1) counter++; }