Handling Signals: Function signal()

The most important function for handling signals is signal(). It has the following function prototype:

void (*signal (int, void (*)(int))) (int);
Here are some explanations:

Example

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

#define   MAX_i    10000
#define   DIVISOR   1000
#define   MAX_j    20000

void  main(void)
{
     int            i;
     unsigned long  j, sum;

     signal(SIGINT, SIG_IGN);        
     printf("CPU-bound loop started.  Pressing Ctrl-C has no effect....\n");
     for (i = 1; i <= MAX_i; i++)  {
          sum = 0;
          for (j = 0; j <= MAX_j; j++)
               sum += j;
          if (i % DIVISOR == 0)
               printf("Iteration %d, sum = %ld\n", i, sum);
     }
     printf("Computation is done.\n\n");

     signal(SIGINT, SIG_DFL);     
     printf("CPU-bound loop restarted.  Pressing Ctrl-C HAS effect now...\n");
     for (i = 1; i <= MAX_i; i++)  {
          sum = 0;
          for (j = 0; j <= MAX_j; j++)
               sum += j;
          if (i % DIVISOR == 0)
               printf("Iteration %d, sum = %ld\n", i, sum);
     }
     printf("Computation is done.\n");
}
The above program has two identical loops. However, before the first loop starts, signal SIGINT is ignored and, as a result, hitting Ctrl-C has no effect. Before the second loop starts, signal SIGINT handling is reset to the default, which means the program is interrupted when Ctrl-C is pressed.