Next: Termination in Handler, Up: Defining Handlers [Contents][Index]
Handlers which return normally are usually used for signals such as
SIGALRM
and the I/O and interprocess communication signals. But
a handler for SIGINT
might also return normally after setting a
flag that tells the program to exit at a convenient time.
It is not safe to return normally from the handler for a program error signal, because the behavior of the program when the handler function returns is not defined after a program error. See Program Error Signals.
Handlers that return normally must modify some global variable in order
to have any effect. Typically, the variable is one that is examined
periodically by the program during normal operation. Its data type
should be sig_atomic_t
for reasons described in Atomic Data Access.
Here is a simple example of such a program. It executes the body of
the loop until it has noticed that a SIGALRM
signal has arrived.
This technique is useful because it allows the iteration in progress
when the signal arrives to complete before the loop exits.
#include <signal.h> #include <stdio.h> #include <stdlib.h> /* This flag controls termination of the main loop. */ volatile sig_atomic_t keep_going = 1; /* The signal handler just clears the flag and re-enables itself. */ void catch_alarm (int sig) { keep_going = 0; signal (sig, catch_alarm); } void do_stuff (void) { puts ("Doing stuff while waiting for alarm...."); } int main (void) { /* Establish a handler for SIGALRM signals. */ signal (SIGALRM, catch_alarm); /* Set an alarm to go off in a little while. */ alarm (2); /* Check the flag once in a while to see when to quit. */ while (keep_going) do_stuff (); return EXIT_SUCCESS; }
Next: Termination in Handler, Up: Defining Handlers [Contents][Index]