Example 4-1 shows how the signal, alarm, and pause functions operate. It also shows how to establish a signal handler to catch a signal, thereby preventing program termination.
/* This program shows how to alternately suspend and resume a *
* program using the signal, alarm, and pause functions. It *
* compiles in /STANDARD=VAXC or /STANDARD=RELAXED_ANSI89 mode. */
#define SECONDS 5
#include <stdio.h>
#include <signal.h>
int number_of_alarms = 5; /* Set alarm counter. */
void alarm_action(int);
main()
{
signal(SIGALRM, alarm_action); /* Establish a signal handler. *
* to catch the SIGALRM signal. */
alarm(SECONDS); /* Set alarm clock for 5 seconds. */
pause(); /* Suspend the process until *
* the signal is received. */
}
void alarm_action(int x)
{
printf("\t<%d\007>", number_of_alarms); /* Print the value of *
* the alarm counter. */
signal(SIGALRM, alarm_action); /* Reset the signal. */
alarm(SECONDS); /* Set the alarm clock. */
if (--number_of_alarms) /* Decrement alarm counter. */
pause();
}
Here is the sample output from Example 4-1:
$ RUN EXAMPLE
<5> <4> <3> <2> <1>