Signals
Overview
The principal function used in C to adjust signals is signal. Note that use of this function in multithreaded programs is explicitly regarded as undefined behavior.
typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler);
The signal function is used to change the action associated with a signal signum in one of three ways:
- If
handlerisSIG_IGN, then signals of typesignumare ignored. - If
handlerisSIG_DFL, then the action for signals of typesignumreverts to the default action. - Other handler is the address of a user-defined function.
On Linux machines, it's generally preferred to instead use sigaction:
int sigaction(int signum,
const struct sigaction *restrict act,
struct sigaction *restrict oldact);)
Signal Mask
To update the signal mask (i.e. the blocked bit vector), sigprocmask() is typically used:
int sigprocmask(int how, const sigset_t *set, sigset_t *oldset);
Other functions include:
int sigemptyset(sigset_t *set);
int sigfillset(sigset_t *set);
int sigaddset(sigset_t *set, int signum);
int sigdelset(sigset_t *set, int signum);
int sigismember(const sigset_t *set, int signum);
Safety
A function is async-signal-safe if and only if it can be safely called from a signal handler. This holds either because it is reentrant or because it cannot be interrupted by a signal handler.
Atomicity
The <signal.h> header also exports the sig_atomic_t type. This is an integer type with a minimal width of 8 bits. Memory-load (evaluation) and store (assignment) are guaranteed atomic; other operations are not.