Skip to content

sigaction()

Purpose

sigaction() installs or queries a signal handler.

It is preferred over the older signal() API because it provides more explicit behavior.

#include <signal.h>

Prototype

int sigaction(int signum, const struct sigaction *act,
              struct sigaction *oldact);

Minimal Example

static volatile sig_atomic_t stop_requested;

static void handle_sigint(int signo)
{
    (void)signo;
    stop_requested = 1;
}

struct sigaction sa = {0};
sa.sa_handler = handle_sigint;
sigemptyset(&sa.sa_mask);

if (sigaction(SIGINT, &sa, NULL) < 0)
    perror("sigaction");

Common Pitfalls

  • Doing too much work inside a signal handler.
  • Calling non-async-signal-safe functions from a handler.
  • Forgetting to initialize sa_mask.
  • Mixing signal handlers with signalfd() without a clear design.