Responding Safely to Unix Signals
A signal is a notification that an event has occurred, such as a termination request or an expired timer. Signal handling lets a program respond without choosing the exact point at which the notification arrives. This lesson uses POSIX interfaces in single-threaded C programs; examples involving coalescing explicitly assume Linux standard signals.
Generation and delivery are different
Generating a signal does not mean its response has already run. Delivery is the point at which the receiving program takes the applicable action. A disposition determines that response.
Disposition | Response | How it is selected |
|---|---|---|
Default | Uses the action defined for that signal | SIG_DFL |
Ignore | Discards the notification | SIG_IGN |
Catch | Invokes a programmer-supplied function | Handler address |
Use sigaction() to establish the disposition. For example, catching SIGTERM can let normal program execution perform an orderly shutdown. SIGKILL and SIGSTOP cannot be caught, blocked, or ignored, so they cannot support a cleanup handler.
A signal handler interrupts the current execution path. If it returns normally, execution resumes through the saved context. Its timing therefore matters even when the program has only one thread.
Masks defer delivery
The signal mask is the set of signals whose delivery is currently blocked. A caught signal generated while blocked becomes pending. Blocking changes delivery timing; it does not install a handler or select an ignore disposition.
For a single-threaded program, sigprocmask() changes this set. If B is the current mask and S is the supplied set, the governing rules are:
Save the old mask when temporarily blocking signals, then restore that exact mask afterward. Emptying the mask instead could accidentally unblock signals that were already blocked for another reason. In multithreaded programs, masks belong to individual threads and pthread_sigmask() is the appropriate interface.
On Linux, repeated instances of the same standard signal coalesce while pending. One pending SIGUSR1 therefore means at least one notification occurred, rather than recording an exact count.
Keep the handler small
A handler can interrupt library code while its internal state is only partly updated. Calls such as printf() and malloc() are not guaranteed to be async-signal-safe. A function being safe between threads does not by itself establish safety inside a handler.
A useful pattern is to assign a flag and let ordinary execution do the substantial work:
static volatile sig_atomic_t stop_requested = 0;
static void on_term(int signo)
{
(void)signo;
stop_requested = 1;
}The type sig_atomic_t supports this simple communication pattern. volatile ensures accesses are performed as required, but does not make a compound sequence indivisible.
When installing this handler, initialize sa_mask with sigemptyset() and choose sa_flags explicitly. Normally, the signal being handled is also blocked during its handler. sa_mask specifies additional signals to block during that execution.
Check and wait without a gap
The sequence if (!stop_requested) pause(); has a race. The handler might set the flag after the test but before pause(). The program then waits despite already having received its notification.
Block the relevant signal before checking the flag. While the flag remains zero, call sigsuspend() with a temporary mask that unblocks that signal. This operation replaces the mask and waits atomically, closing the check-then-sleep gap. After a caught handler returns, sigsuspend() restores the mask that was active before the call. Recheck the flag because another caught signal could have caused the return.
What to remember
- Dispositions select responses; masks control delivery timing.
- Linux standard signals can coalesce while pending.
- Assign a simple flag in the handler and defer substantial work.
- Block before testing, use sigsuspend() to wait, and restore the saved mask.
Example: Waiting for a Configuration Reload
A single-threaded Linux logging utility uses the standard signal SIGUSR1 to request a configuration reload. Before any sender is enabled, the utility initializes a static volatile sig_atomic_t flag named reload_requested to 0, blocks SIGUSR1, and installs a handler that assigns 1 to the flag and returns.
The initial signal mask was empty, and no signal was initially pending. Four reload requests generate SIGUSR1 at 12 ms, 18 ms, 26 ms, and 30 ms. At 35 ms, the main program tests the flag while the signal remains blocked. At 40 ms, it calls sigsuspend() with the saved empty mask. Assume delivery and handler execution occur at 40 ms with negligible execution time. No other signals occur, and all setup calls succeed.
a) At 35 ms, how many instances of SIGUSR1 are pending, and what value does reload_requested hold?
- Count the generations before the test. All four request times precede 35 ms, so the number of generations is ________.
- Apply Linux standard-signal coalescing. The first generation makes SIGUSR1 pending. The later generations occur while that same signal remains blocked and pending, so they do not create additional queued instances.
- Determine whether the handler has run. Because delivery remains blocked, the handler has not executed and has not changed the initialized flag.
At 35 ms, one instance is pending and reload_requested equals 0. Pending status records a notification awaiting delivery; it is separate from the application's flag.
b) How many handler invocations result when the signal is unblocked at 40 ms? Find the notification latency, defined here as the elapsed time from the earliest request to the first handler execution. Give the latency in milliseconds.
- Count pending instances rather than generations. There is one pending SIGUSR1, so unblocking produces one handler invocation under the stated assumptions. That invocation assigns 1 to reload_requested.
- Identify the times used for latency. The earliest request occurs at ________, and handler execution occurs at ________.
- Subtract the request time from the execution time:
The results are one handler invocation and a notification latency of 28 ms. Measuring from the final request would describe a different interval, rather than the latency defined in this part.
c) Write a protected waiting pattern that lets normal execution reload the configuration after receiving the notification. Explain why the pending request cannot be lost between checking the flag and sleeping.
- Block SIGUSR1 and save the previous mask before enabling any sender. Install the handler while the signal is blocked. The handler only sets the flag; normal execution performs the reload.
- Test the flag while SIGUSR1 remains blocked. If the flag is zero, call sigsuspend() with the saved mask, which unblocks SIGUSR1. The mask replacement and wait are atomic.
- Recheck the flag after each return, then restore the saved mask before continuing. The following program shows the pattern; the sender is enabled externally only after setup is complete, and the waiting calls use valid masks.
#define _POSIX_C_SOURCE 200809L
#include "signal.h"
#include "stddef.h"
static volatile sig_atomic_t reload_requested = 0;
static void on_reload(int signo)
{
(void)signo;
reload_requested = 1;
}
int main(void)
{
sigset_t blocked, previous;
struct sigaction action = {0};
sigemptyset(&blocked);
sigaddset(&blocked, SIGUSR1);
if (sigprocmask(SIG_BLOCK, &blocked, &previous) == -1)
return 1;
action.sa_handler = on_reload;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
if (sigaction(SIGUSR1, &action, NULL) == -1)
return 1;
while (!reload_requested)
sigsuspend(&previous);
if (sigprocmask(SIG_SETMASK, &previous, NULL) == -1)
return 1;
/* Reload configuration here in normal execution. */
return 0;
}A lost wakeup would occur if the notification were handled after the flag test but before an unprotected wait, leaving the program asleep despite the flag being set. Here, SIGUSR1 stays blocked between the test and sigsuspend(). The pending request is delivered when the temporary mask unblocks it, the handler sets the flag to 1, and the next test exits the loop. Restoring the saved mask preserves the delivery policy that existed before setup.
A Linux service developer wants to intercept every signal so the service can save its state. Complete the two exceptions using symbolic signal names: terminates a process, while stops it; neither signal can be caught, blocked, or ignored.
A signal mask lists signals whose delivery is blocked. A single-threaded POSIX program initially blocks only SIGUSR1. It then performs the three successful sigprocmask() operations shown below, in order. Complete each row for the mask immediately after that operation. Enter exact integers: 1 means blocked and 0 means unblocked.
| Operation in sequence | SIGUSR1 blocked | SIGUSR2 blocked | SIGTERM blocked |
| SIG_BLOCK with SIGTERM | |||
| SIG_UNBLOCK with SIGUSR1 | |||
| SIG_SETMASK with SIGUSR2 |