Catching multiple types of signals is as easy as catching one type as discussed on the previous page. There are two choices:
signal(SIGINT, INThandler);
signal(SIGQUIT, QUIThandler);
void INThandler(int sig)
{
..........
}
void QUIThandler(int sig)
{
..........
}
It is important to remind you that in a signal handler you might
want to disable all signals, including the one
this handler is processing. This is because you perhaps do not
want to be interrupted while the current signal is being processed.
Of course, it is your choice. In some applications, you might want
to disable some signals in a handler and allow some others to occur.
signal(SIGINT, SIGhandler);
signal(SIGALRM, SIGhandler);
..........
void SIGhandler(int sig)
{
..........
switch (sig) {
case SIGINT : .....
case SIGALRM : .....
..........
default : .....
}
..........
}
In the above example, SIGhandler() is installed to handle
more than one signals. When it is called, the argument
sig contains the signal name that should be processed.
A switch statement is used to separate different
signals. As always, disabling some signals may be required.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#define MAX_i 10000
#define MAX_j 20000
#define MAX_SECOND (2)
void INThandler(int);
void ALARMhandler(int);
int SECOND;
int i, j;
void INThandler(int sig)
{
char c;
signal(SIGINT, SIG_IGN);
signal(SIGALRM, SIG_IGN);
printf("*** INT handler --> You just hit Ctrl-C\n");
printf("*** INT handler --> current values of i and j = %d and %d\n",
i, j);
printf("*** INT handler --> Do you really want to quit? [y/n] ");
c = tolower(getchar());
if (c == 'y') {
printf("*** INT handler --> Program halts due to your request.\n");
exit(0);
}
signal(SIGINT, INThandler);
signal(SIGALRM, ALARMhandler);
alarm(SECOND);
}
void ALARMhandler(int sig)
{
signal(SIGINT, SIG_IGN);
signal(SIGALRM, SIG_IGN);
printf("*** ALARM handler --> an alarm signal arrives\n");
printf("*** ALARM handler --> current values of i and j = %d and %d\n",
i, j);
alarm(SECOND);
signal(SIGINT, INThandler);
signal(SIGALRM, ALARMhandler); /
}
void main(int argc, char *argv[])
{
long sum;
if (argc != 2) {
printf("Use: %s time-interval\n", argv[0]);
printf("Time interval set to default (%d).\n", MAX_SECOND);
SECOND = MAX_SECOND;
}
else {
SECOND = abs(atoi(argv[1]));
if (SECOND == 0) {
printf("Time interval must be positive. Use default (%d).\n",
MAX_SECOND);
SECOND = MAX_SECOND;
}
}
signal(SIGINT, INThandler);
signal(SIGALRM, ALARMhandler);
alarm(SECOND);
for (i = 1; i <= MAX_i; i++) {
sum = 0;
for (j = 0; j <= MAX_j; j++)
sum += j;
}
printf("Computation is done.\n\n");
}