SIGACTION(2)
π SIGACTION(2) π
okay bestie, sit down, hydrate, because we're talking about sigaction β the software signal facilities β and she is that girl. this is sigaction(2), a system call, and yes we're doing the whole thing together, no skimming, no skipping. π«Ά
β¨ NAME β¨
sigaction β software signal facilities π
π LIBRARY π
Standard C Library β that's libc, link it with -lc. classic. iconic. no notes. β¨
πΈ SYNOPSIS πΈ
first things first, you gotta invite her in:
#include <signal.h>
and here's the struct, the whole vibe, look at her:
struct sigaction {
void (*sa_handler)(int);
void (*sa_sigaction)(int, siginfo_t *, void *);
int sa_flags; /* see signal options below */
sigset_t sa_mask; /* signal mask to apply */
};
ok so quick tour, because this struct is giving main character energy:
sa_handleris a function pointer βvoid (*)(int), she takes oneintand returns nothing. πsa_sigactionis the other function pointer βvoid (*)(int, siginfo_t *, void *), three args, also returns nothing. two handlers, one struct, we contain multitudes.sa_flagsis anintβ and the comment literally says/* see signal options below */, so like, stay tuned bestie.sa_maskis asigset_tβ the/* signal mask to apply */, exactly as written. no cap.
and then the actual call, the moment we've all been waiting for:
int
sigaction(int sig, const struct sigaction * restrict act,
struct sigaction * restrict oact);
she returns an int, she takes sig, a const struct sigaction * restrict act, and a struct sigaction * restrict oact. yes both restrict, yes it matters, yes we love a qualified pointer. π₯
and that's just part one bestie, don't go anywhere β more of this page is coming and it only gets better. π¦
β¨ DESCRIPTION β¨
okay so bestie, the system defines a whole set of signals that may be delivered to a process. π Signal delivery is literally giving hardware interrupt energy: the signal is normally blocked from further occurrence, the current thread context is saved, and a new one is built. A process may specify a handler to which a signal is delivered, or specify that a signal is to be ignored. A process may also specify that a default action is to be taken by the system when a signal occurs. A signal may also be blocked for a thread, in which case it will not be delivered to that thread until it is unblocked. The action to be taken on delivery is determined at the time of delivery. Normally, signal handlers execute on the current stack of the thread. This may be changed, on a per-handler basis, so that signals are taken on a special signal stack. π¦
Signal routines normally execute with the signal that caused their invocation blocked, but other signals may yet occur. A global signal mask defines the set of signals currently blocked from delivery to a thread. The signal mask for a thread is initialized from that of its parent (normally empty). It may be changed with a sigprocmask(2) or pthread_sigmask(3) call, or when a signal is delivered to the thread.
When a signal condition arises for a process or thread, the signal is added to a set of signals pending for the process or thread. Whether the signal is directed at the process in general or at a specific thread depends on how it is generated. For signals directed at a specific thread, if the signal is not currently blocked by the thread then it is delivered to the thread. For signals directed at the process, if the signal is not currently blocked by all threads then it is delivered to one thread that does not have it blocked (the selection of which is unspecified). Signals may be delivered any time a thread enters the operating system (e.g., during a system call, page fault or trap, or clock interrupt). If multiple signals are ready to be delivered at the same time, any signals that could be caused by traps are delivered first. Additional signals may be processed at the same time, with each appearing to interrupt the handlers for the previous signals before their first instructions. The set of pending signals is returned by the sigpending(2) system call. When a caught signal is delivered, the current state of the thread is saved, a new signal mask is calculated (as described below), and the signal handler is invoked. The call to the handler is arranged so that if the signal handling routine returns normally the thread will resume execution in the context from before the signal's delivery. If the thread wishes to resume in a different context, then it must arrange to restore the previous context itself. π
When a signal is delivered to a thread a new signal mask is installed for the duration of the process' signal handler (or until a sigprocmask(2) system call is made). This mask is formed by taking the union of the current signal mask set, the signal to be delivered, and the signal mask associated with the handler to be invoked.
The sigaction() system call assigns an action for a signal specified by sig. If act is non-NULL, it specifies an action (SIG_DFL, SIG_IGN, or a handler routine) and mask to be used when delivering the specified signal. If oact is non-NULL, the previous handling information for the signal is returned to the user.
The above declaration of struct sigaction is not literal. It is provided only to list the accessible members. See <sys/signal.h> for the actual definition. In particular, the storage occupied by sa_handler and sa_sigaction overlaps, and it is nonsensical for an application to attempt to use both simultaneously. π
Once a signal handler is installed, it normally remains installed until another sigaction() system call is made, or an execve(2) is performed. A signal-specific default action may be reset by setting sa_handler to SIG_DFL. The defaults are process termination, possibly with core dump; no action; stopping the process; or continuing the process. See the signal list below for each signal's default action. If sa_handler is SIG_DFL, the default action for the signal is to discard the signal, and if a signal is pending, the pending signal is discarded even if the signal is masked. If sa_handler is set to SIG_IGN current and pending instances of the signal are ignored and discarded.
Options may be specified by setting sa_flags. The meaning of the various bits is as follows:
SA_NOCLDSTOPβ If this bit is set when installing a catching function for theSIGCHLDsignal, theSIGCHLDsignal will be generated only when a child process exits, not when a child process stops. πΆSA_NOCLDWAITβ If this bit is set when callingsigaction()for theSIGCHLDsignal, the system will not create zombie processes when children of the calling process exit. If the calling process subsequently issues await(2)(or equivalent), it blocks until all of the calling process's child processes terminate, and then returns a value of-1witherrnoset toECHILD. The same effect of avoiding zombie creation can also be achieved by settingsa_handlerforSIGCHLDtoSIG_IGN. π§SA_ONSTACKβ If this bit is set, the system will deliver the signal to the process on a signal stack, specified by each thread withsigaltstack(2). πSA_NODEFERβ If this bit is set, further occurrences of the delivered signal are not masked during the execution of the handler. πSA_RESETHANDβ If this bit is set, the handler is reset back toSIG_DFLat the moment the signal is delivered. β»οΈSA_RESTARTβ See paragraph below. πSA_SIGINFOβ If this bit is set, the handler function is assumed to be pointed to by thesa_sigactionmember ofstruct sigactionand should match the prototype shown above or as below inβEXAMPLESβ. This bit should not be set when assigningSIG_DFLorSIG_IGN. π‘
If a signal is caught during the system calls listed below, the call may be forced to terminate with the error EINTR, the call may return with a data transfer shorter than requested, or the call may be restarted. Restart of pending calls is requested by setting the SA_RESTART bit in sa_flags. The affected system calls include open(2), read(2), write(2), sendto(2), recvfrom(2), sendmsg(2) and recvmsg(2) on a communications channel or a slow device (such as a terminal, but not a regular file) and during a wait(2) or ioctl(2). However, calls that have already committed are not restarted, but instead return a partial success (for example, a short read count). π₯
After a pthread_create(3) the signal mask is inherited by the new thread and the set of pending signals and the signal stack for the new thread are empty.
After a fork(2) or vfork(2) all signals, the signal mask, the signal stack, and the restart/interrupt flags are inherited by the child.
The execve(2) system call reinstates the default action for all signals which were caught and resets all signals to be caught on the user stack. Ignored signals remain ignored; the signal mask remains the same; signals that restart pending system calls continue to do so.
The following is a list of all signals with names as in the include file <signal.h>. The columns are NAME, Default Action, Description β got it? Now the whole squad, no cap:
SIGHUPβ default action: terminate process; terminal line hangupSIGINTβ default action: terminate process; interrupt programSIGQUITβ default action: create core image; quit programSIGILLβ default action: create core image; illegal instructionSIGTRAPβ default action: create core image; trace trapSIGABRTβ default action: create core image; abort(3) call (formerly SIGIOT)SIGEMTβ default action: create core image; emulate instruction executedSIGFPEβ default action: create core image; floating-point exceptionSIGKILLβ default action: terminate process; kill programSIGBUSβ default action: create core image; bus errorSIGSEGVβ default action: create core image; segmentation violationSIGSYSβ default action: create core image; non-existent system call invokedSIGPIPEβ default action: terminate process; write on a pipe with no readerSIGALRMβ default action: terminate process; real-time timer expiredSIGTERMβ default action: terminate process; software termination signalSIGURGβ default action: discard signal; urgent condition present on socketSIGSTOPβ default action: stop process; stop (cannot be caught or ignored)SIGTSTPβ default action: stop process; stop signal generated from keyboardSIGCONTβ default action: discard signal; continue after stopSIGCHLDβ default action: discard signal; child status has changedSIGTTINβ default action: stop process; background read attempted from control terminalSIGTTOUβ default action: stop process; background write attempted to control terminalSIGIOβ default action: discard signal; I/O is possible on a descriptor (see fcntl(2))SIGXCPUβ default action: terminate process; cpu time limit exceeded (see setrlimit(2))SIGXFSZβ default action: terminate process; file size limit exceeded (see setrlimit(2))SIGVTALRMβ default action: terminate process; virtual time alarm (see setitimer(2))SIGPROFβ default action: terminate process; profiling timer alarm (see setitimer(2))SIGWINCHβ default action: discard signal; window size changeSIGINFOβ default action: discard signal; status request from keyboardSIGUSR1β default action: terminate process; user defined signal 1SIGUSR2β default action: terminate process; user defined signal 2
bestie, quick heads-up: thesa_maskfield inactis not allowed to blockSIGKILLorSIGSTOP. like, it's just not. any attempt to do so gets silently ignored β no error, no nothing, the kernel just goes "mmm no π " and moves on.
β¨ THE ASYNC-SIGNAL SAFE LIST (aka the safe-to-call-in-a-handler club) β¨
okay so these functions are either reentrant or not interruptible by signals, which makes them async-signal safe. translation: you can call them from signal-catching functions or from a child process after calling fork(2) in a multi-threaded process β no restrictions, no worries, go off π«Ά
πΈ Base Interfaces:
_Exit(), _exit(), accept(), access(), alarm(), bind(), cfgetispeed(), cfgetospeed(), cfsetispeed(), cfsetospeed(), chdir(), chmod(), chown(), close(), connect(), creat(), dup(), dup2(), execl(), execle(), execv(), execve(), faccessat(), fchdir(), fchmod(), fchmodat(), fchown(), fchownat(), fcntl(), fork(), fstat(), fstatat(), fsync(), ftruncate(), getegid(), geteuid(), getgid(), getgroups(), getpeername(), getpgrp(), getpid(), getppid(), getsockname(), getsockopt(), getuid(), kill(), link(), linkat(), listen(), lseek(), lstat(), mkdir(), mkdirat(), mkfifo(), mkfifoat(), mknod(), mknodat(), open(), openat(), pause(), pipe(), poll(), pselect(), pthread_sigmask(), raise(), read(), readlink(), readlinkat(), recv(), recvfrom(), recvmsg(), rename(), renameat(), rmdir(), select(), send(), sendmsg(), sendto(), setgid(), setpgid(), setsid(), setsockopt(), setuid(), shutdown(), sigaction(), sigaddset(), sigdelset(), sigemptyset(), sigfillset(), sigismember(), signal(), sigpending(), sigprocmask(), sigsuspend(), sleep(), sockatmark(), socket(), socketpair(), stat(), symlink(), symlinkat(), tcdrain(), tcflow(), tcflush(), tcgetattr(), tcgetpgrp(), tcsendbreak(), tcsetattr(), tcsetpgrp(), time(), times(), umask(), uname(), unlink(), unlinkat(), utime(), wait(), waitpid(), write().
π X/Open Systems Interfaces:
sigpause(), sigset(), utimes().
β Realtime Interfaces:
aio_error(), clock_gettime(), timer_getoverrun(), aio_return(), fdatasync(), sigqueue(), timer_gettime(), aio_suspend(), sem_post(), timer_settime().
π¦ Base Interfaces not specified as async-signal safe by POSIX:
fpathconf(), pathconf(), sysconf().
π§ Base Interfaces not specified as async-signal safe by POSIX, but planned to be:
ffs(), htonl(), htons(), memccpy(), memchr(), memcmp(), memcpy(), memmove(), memset(), ntohl(), ntohs(), stpcpy(), stpncpy(), strcat(), strchr(), strcmp(), strcpy(), strcspn(), strlen(), strncat(), strncmp(), strncpy(), strnlen(), strpbrk(), strrchr(), strspn(), strstr(), strtok_r(), wcpcpy(), wcpncpy(), wcscat(), wcschr(), wcscmp(), wcscpy(), wcscspn(), wcslen(), wcsncat(), wcsncmp(), wcsncpy(), wcsnlen(), wcspbrk(), wcsrchr(), wcsspn(), wcsstr(), wcstok(), wmemchr(), wmemcmp(), wmemcpy(), wmemmove(), wmemset().
π Extension Interfaces:
accept4(), bindat(), close_range(), closefrom(), connectat(), eaccess(), ffsl(), ffsll(), flock(), fls(), flsl(), flsll(), futimesat(), pipe2(), strlcat(). strlcpy(), strsep().
oh and btw, reading or writing errno is async-signal safe. little icon behaviour tbh.
every single function NOT in the lists above is considered unsafe with respect to signals, periodt. what that means: the behaviour of such functions is undefined when they're called from a signal handler that interrupted an unsafe function π like... genuinely undefined, bestie, that's not a vibe.
general life advice from the manpage: signal handlers should do little more than set a flag. most other actions are just not safe. it's giving "keep it minimal" energy.
Also, it's good practice to make a copy of the global variable errno and restore it before returning from the signal handler π«Ά this protects against the side effect of errno being set by functions called from inside the signal handler. (yes, even the safe ones can touch it. protect your errno, she's fragile π
)
β¨ RETURN VALUES β¨
The sigaction() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error. that's it, that's the whole thing π
β¨ EXAMPLES β¨
okay so there are three possible prototypes your handler may match, and you gotta pick the right one or it's chaos:
ANSI C:
void handler(int);
Traditional BSD style:
void handler(int, int code, struct sigcontext *scp);
POSIX SA_SIGINFO:
void handler(int, siginfo_t *info, ucontext_t *uap);
The handler function should match the SA_SIGINFO prototype if the SA_SIGINFO bit is set in sa_flags β. It then should be pointed to by the sa_sigaction member of struct sigaction. and note β you should NOT assign SIG_DFL or SIG_IGN this way π that's not what those members are for.
If the SA_SIGINFO flag is not set, the handler function should match either the ANSI C or traditional BSD prototype and be pointed to by the sa_handler member of struct sigaction.
In practice, FreeBSD always sends the three arguments of the latter and since the ANSI C prototype is a subset, both will work π
. The sa_handler member declaration in FreeBSD include files is that of ANSI C (as required by POSIX), so a function pointer of a BSD-style function needs to be casted to compile without warning. The traditional BSD style is not portable and since its capabilities are a full subset of a SA_SIGINFO handler, its use is deprecated. like, it's giving legacy. don't.
The sig argument is the signal number, one of the SIG... values from <signal.h>.
The code argument of the BSD-style handler and the si_code member of the info argument to a SA_SIGINFO handler contain a numeric code explaining the cause of the signal, usually one of the SI_... values from <sys/signal.h> or codes specific to a signal, i.e., one of the FPE_... values for SIGFPE.
The scp argument to a BSD-style handler points to an instance of struct sigcontext.
The uap argument to a POSIX SA_SIGINFO handler points to an instance of ucontext_t.
β¨ ERRORS β¨
The sigaction() system call will fail and no new signal handler will be installed if one of the following occurs π
[EINVAL]β Thesigargument is not a valid signal number. (like, that's not a real signal bestie π« )[EINVAL]β An attempt is made to ignore or supply a handler forSIGKILLorSIGSTOP. (these two are untouchable. the kernel said no. respect it.)
β¨ SEE ALSO β¨
kill(1), kill(2), ptrace(2), setitimer(2), setrlimit(2), sigaltstack(2), sigpending(2), sigprocmask(2), sigsuspend(2), wait(2), fpsetmask(3), setjmp(3), siginfo(3), siginterrupt(3), sigsetops(3), ucontext(3), tty(4)
(go read these next, they're the whole friend group π«Ά)
β¨ STANDARDS β¨
The sigaction() system call is expected to conform to ISO/IEC 9945-1:1990 (βPOSIX.1β) π
The SA_ONSTACK and SA_RESTART flags are Berkeley extensions, as are the signals SIGTRAP, SIGEMT, SIGBUS, SIGSYS, SIGURG, SIGIO, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH, and SIGINFO. Those signals are available on most BSD-derived systems π
The SA_NODEFER and SA_RESETHAND flags are intended for backwards compatibility with other operating systems.
The SA_NOCLDSTOP, and SA_NOCLDWAIT flags are featuring options commonly found in other operating systems.
The flags are approved by Version 2 of the Single UNIX Specification (βSUSv2β), along with the option to avoid zombie creation by ignoring SIGCHLD π§β¨ (yes that's real, ignoring SIGCHLD means no zombies, iconic behaviour)
okay bestie that's the whole page π you now know more about signal handling than 99% of people at the party. go forth and install handlers responsibly β¨
this page is from the Debian crew, dated June 29, 2020, and it's the SIGACTION(2) manual β mwah, no notes π
π
π¦ where this page comes from
- debian bookworm: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- debian trixie: freebsd-manpages 12.2-2 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu jammy: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu noble: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu questing: freebsd-manpages 12.2-2
- ubuntu resolute: freebsd-manpages 12.2-2build1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu stonking: freebsd-manpages 12.2-2build1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- Copyright (c) 1980, 1990, 1993 The Regents of the University of California. All rights reserved
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms