Concept

Signal Handling

Definition

Signal handling is the mechanism by which a running process registers callbacks for the asynchronous notifications the operating system can deliver to it. When a signal arrives — a Ctrl-C from the terminal, a polite SIGTERM from a service manager, a SIGHUP because the controlling terminal closed — the kernel interrupts the process and invokes the handler the program installed for that signal. If no handler is installed, the default action runs, which is usually termination.

In shell scripts the handler is registered with the trap builtin, which associates a snippet of shell code with one or more signal names. In C and other compiled languages the equivalent is the sigaction system call, which is also what the shell ultimately invokes under the hood.

Why it matters

How it works

A signal is a small integer delivered asynchronously to a process by the kernel. The process table tracks, for each signal number, an action: default, ignore, or run-this-handler. The trap builtin in bash sets the action by registering a shell snippet against one or more signal names. The classic pattern is to trap EXIT and run a cleanup function regardless of how the script terminates, then trap the common interactive signals so a Ctrl-C also runs the cleanup before propagating the termination.

A handler runs in the context of the interrupted code, which has two implications. First, the handler should be short and avoid functions that are not reentrant; the standard library's stdio buffer, for instance, can corrupt if a handler writes while the main code is mid-write. Second, the handler can choose whether to terminate, continue, or even longjmp out of the interrupted code. In shells the choice is usually simpler: do cleanup, then either exit explicitly or fall through and let the script continue. The two uncatchable signals — SIGKILL and SIGSTOP — exist so the operating system retains a guaranteed mechanism for terminating or pausing any process, no matter how badly behaved.

Where it goes next

Continue exploring

Tags