Signals (Slides)

Signals are poor notifications to a process

Example Signals

SIGINT Ctrl-C termination
SIGTSTP Ctrl-Z suspend
SIGTERM kill <pid> termination
SIGALRM Timer expiration termination

Terminology

man -s 7 signal.

Default Actions

All signals have a predefined default action

Important Signals

Signal Default Action Reason
SIGABRT Terminate(core) E.g. assert()
SIGSEGV Terminate(core) Access violation
SIGBUS Terminate(core) Access violation
SIGILL Terminate(core) Bogus function pointer
SIGFPE Terminate(core) Floating point
SIGINT Terminate Ctrl-C
SIGTERM Terminate Explicit kill
SIGPIPE Terminate Write to pipe/socket
SIGCHLD Ignore Child death

Sending, Commandline

$ kill -l
... signals here ...
$ kill 1234   # to PID
$ kill -SEGV 1234   # kill as if segfaulted
$ killall firefox

man -s 1 kill

Sending Signals, Programmatically

int kill(pid_t pid, int sig);

man -s 2 kill

Warning!

Blocking Signals: Signal Mask

Signal Mask

Signal Mask Manipulation

int sigprocmask(int how, const sigset_t *set, sigset_t *oldset);

man -s 2 sigprocmask

Pending Signals

int sigpending(sigset_t *set);

Boring ...

man -s 2 sigpending

Signal Set: sigset_t

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);

man -s 3 sigsetops

Signal Handlers

void handler(int sig);

Installing a Signal Handler (1)

struct sigaction {
    void     (*sa_handler)(int);
    sigset_t   sa_mask;
    int        sa_flags;
};
int sigaction(int signum,
    const struct sigaction *act,
    struct sigaction *oldact);

man -s 2 sigaction

Installing a Signal Handler (2)

Effects of Signal Delivery

E.g. terminate a program based upon the value of a flag (by dropping out of a loop) that is set in a signal handler. Use ...

volatile sig_atomic_t flag;

Last Warning!

Signals are delivered asynchronously

man -s 7 signal-safety

WTF Async Signal Safe?

The following functions (among many others) are not async-signal-safe

Exercise: Signals

Write a program that ...