Let us extend the previous example to handle two types of signals. We choose to work with SIGINT and SIGALRM (alarm clock).
Here is a simple example. Click here to download a copy of this program.
Let us start with the two signal handlers INThandler() and ALARMhandler():
void INThandler(int sig)
{
char c;
signal(SIGALRM, SIG_IGN);
signal(SIGINT, SIG_IGN);
printf("OUCH, you just hit a Ctrl-C\n"
"Do you really want to quit? [y/n] ");
c = getchar();
if (c == 'y' || c == 'Y')
exit(0);
signal(SIGINT, INThandler);
signal(SIGALRM, ALARMhandler);
longjmp(JumpBuffer, FROM_CTRL_C);
}
void ALARMhandler(int sig)
{
signal(SIGINT, SIG_IGN);
signal(SIGALRM, SIG_IGN);
printf("An alarm signal just arrived ...\n");
alarm(0);
signal(SIGALRM, ALARMhandler);
signal(SIGINT, INThandler);
longjmp(JumpBuffer, FROM_ALARM);
}
The main program is simple and is shown below:
#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#define START 0
#define FROM_CTRL_C 1
#define FROM_ALARM 2
#define ALARM 5
jmp_buf JumpBuffer;
void INThandler(int);
void ALARMhandler(int);
void main(void)
{
int JumpReturn;
signal(SIGINT, INThandler);
signal(SIGALRM, ALARMhandler);
while (1) {
if ((JumpReturn = setjmp(JumpBuffer)) == START) {
alarm(ALARM);
pause();
}
else if (JumpReturn == FROM_CTRL_C) {
}
else if (JumpReturn == FROM_ALARM) {
printf("Alarm clock reset to %d sec\n", ALARM);
}
}
}