sigaction() — Linux system interface
Inspect or change signal disposition. Initialize the action and its mask; choose either sa_handler or SA_SIGINFO with sa_sigaction. Handlers run asynchronously: use only async-signal-safe operations, or set a volatile sig_atomic_t flag. SA_RESTART does not restart every interrupted call. SIGKILL and SIGSTOP cannot be caught. Restore the former action when appropriate. EINVAL can indicate an invalid signal or prohibited disposition. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. POSIX interface; tested on Linux/glibc only. These are libc-facing signatures, not raw architecture-specific syscall ABIs.
Formal Syntax & Structure
#include <signal.h>int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| signum | int | Signal whose disposition is queried or set. |
| act | const struct sigaction * | New action, or NULL to query only. |
| oldact | struct sigaction * | Storage for previous action, or NULL. |
Return Value
0 on success. On failure, returns -1 and sets errno.
Working Example
#define _GNU_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <signal.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \ fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \ return EXIT_FAILURE; \} } while (0)
static volatile sig_atomic_t seen;static void handler(int sig) { (void)sig; seen = 1; }
int main(void){ struct sigaction act = {0}, old; sigset_t set, previous; act.sa_handler = handler; CHECK(sigemptyset(&act.sa_mask) == 0); CHECK(sigemptyset(&set) == 0); CHECK(sigaddset(&set, SIGUSR1) == 0); CHECK(sigaction(SIGUSR1, &act, &old) == 0); CHECK(sigprocmask(SIG_UNBLOCK, &set, &previous) == 0); CHECK(raise(SIGUSR1) == 0); CHECK(seen == 1); CHECK(sigaction(SIGUSR1, &old, NULL) == 0); CHECK(sigprocmask(SIG_SETMASK, &previous, NULL) == 0); puts("handler flag set; original action restored"); return EXIT_SUCCESS;}