CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 3 of 6 · 2 min read

Handlers

In plain words: A handler is an ordinary C function that takes the signal number. The call sigaction registers it. The program below sends SIGUSR1 to itself:

#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>

static volatile sig_atomic_t got = 0;
static void on_usr1(int sig) { got = sig; }

int main(void) {
    struct sigaction sa;
    memset(&sa, 0, sizeof sa);
    sa.sa_handler = on_usr1;
    sigemptyset(&sa.sa_mask);
    if (sigaction(SIGUSR1, &sa, NULL) != 0) { perror("sigaction"); return 1; }
    printf("pid %d: sending SIGUSR1 to myself\n", (int)getpid());
    kill(getpid(), SIGUSR1);
    printf("handler saw signal %d\n", (int)got);
    return 0;
}

Output:

pid 296: sending SIGUSR1 to myself
handler saw signal 10

The handler ran in the middle of main, right after kill, stored the number 10 and returned. Then main carried on. The handler is called at an unpredictable point of the program, just as an interrupt handler is called between two instructions (Level 0, page 5).

Two details matter. The variable is volatile sig_atomic_t. A sig_atomic_t is an integer type whose reads and writes cannot be torn into pieces by a signal, and volatile stops the compiler from keeping the variable in a register that the handler cannot update. This is the safe way to pass a message from a handler to the rest of the program.

The second detail is the old function signal. Its behaviour varies between systems, so sigaction is the portable choice.

A second program shows that a process can be signalled by another one. The parent installs a handler for SIGINT and forks a child that sends it three times, 10 ms apart. The parent printed SIGINT handled 3 times. If signals of the same kind arrive faster than the process can run, they merge, so the count can be lower. Signals are notifications, and they are not a queue of messages.

Signal handler

A signal handler is a function that a process registers, usually with sigaction, so that the kernel runs it when a particular signal is delivered to that process. When the handler returns, the process resumes at the point where it was interrupted.

Example: a program registers a handler for SIGTERM that sets a flag, and the main loop checks the flag so it can save its work before it ends.

Check yourself: 1. Why is the shared variable of type volatile sig_atomic_t? 2. At what point does the handler run? 3. Can three quick SIGINT signals be received as one?