Install a Signal Handler

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:

Example 1

The following is a very simple example. Click here to download this program.
#include  <stdio.h>
#include  <signal.h>

void     INThandler(int);

void  main(void)
     signal(SIGINT, INThandler);
     while (1)

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')
          signal(SIGINT, INThandler);

Example 2

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);      
     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");
     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;                  
     printf("Alarm set to %d seconds and is ticking now.....\n", SECOND);
     while (1)