The most important function for handling signals is signal(). It has the following function prototype:
Here are some explanations:void (*signal (int, void (*)(int))) (int);
In fact, what signal() returns is the previously installed handler.void (*)(int)
which accepts an integer argument and returns nothing. This is the function that will handle the signal specified in the first argument. This function is called a signal handler. More precisely, if the system detects the signal specified in the first argument, the signal handler as specified in the second argument is called.void (*)(int)
The above specifies that the signal handler for signal SIGINT is function CtrlCHandler().signal(SIGINT, CtrlCHandler)
In the above two lines, SIGINT and SIGALRM are ignored.signal(SIGINT, SIG_IGN) signal(SIGALRM, SIG_IGN)
The above line asks the system to handle SIGALRM in a defaulted way.signal(SIGALRM, SIG_DFL)
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.#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"); }