11.5 Signals, Interrupts, and Cancellation

OPERATING SYSTEMSSTATUS: DEVELOPINGLEVEL: INTROREVIEWED: 2026-11-18
Concepts signalsyscall

The operating system uses signals to tell a process about asynchronous events: the user pressed Ctrl-C, a child process exited, the program divided an integer by zero. A signal interrupts whatever code is running. Knowing when a handler can run safely, and what work can be cancelled, explains the constraints on interrupt handling in R and in parallel workers.

11.5.1 Mental model

A signal is an asynchronous notification from the operating system to a process. Asynchronous means the process does not know when the signal will arrive. It can arrive between any two instructions, or while the process is blocked in a system call.

A process can define a signal handler, a function that runs when a signal arrives. The kernel interrupts the current code, runs the handler, and then resumes the code where it stopped.

Common signals are SIGINT (Ctrl-C), SIGTERM (termination request), SIGCHLD (child process exited), and SIGSEGV (segmentation fault). Each signal has a default behavior. SIGINT kills the process. SIGCHLD is ignored by default. A process can change the handler for most signals.

11.5.2 Signal delivery

When a signal is sent to a process, the OS marks the process as having a pending signal. When the process next runs, the kernel delivers it: it takes the default action, ignores the signal, or runs the handler. If the process was blocked in a system call when a handler ran, the call is cut short, as the section on system call interruption below explains.

Signal handlers run in the same process and thread that received the signal. The interrupted code is paused. The handler runs to completion. Then the interrupted code resumes.

signal delivery one thread running ordinary code SIGINT arrives handler runs code resumes where it stopped may call only async-signal-safe functions a blocked system call returns EINTR or restarts

The handler runs on the interrupted thread, in the middle of whatever that thread was doing, which is why it may call only async-signal-safe functions.

System call interruption

A slow system call, such as a read waiting for input, is cut short when a handler runs. Unless the handler was installed with SA_RESTART, the call returns early with the error EINTR (“interrupted system call”), and the program must retry it or act on the signal and move on. A few calls fail with EINTR even under SA_RESTART.

Signal safety

A signal handler can run at any moment. It can run in the middle of a malloc. The handler must not call functions that are not async-signal-safe.

Async-signal-safe functions are the ones POSIX guarantees can be called from a handler. Most are thin wrappers around system calls, such as write, signal and _exit. Plain exit is not on the list, because it flushes stdio buffers and runs atexit handlers. Functions that allocate memory, take locks, or keep internal state such as stdio buffers are not safe.

void handler(int sig) {
  printf("SIGINT\n");  // NOT safe: printf works on stdio's shared buffer
  write(STDOUT_FILENO, "SIGINT\n", 7);  // safe
}

The set of safe functions is small. The Linux signal-safety(7) page lists about 190 of them. Most library functions are not on the list.

R’s own SIGINT handler stays inside these rules. It sets the flag R_interrupts_pending and reinstalls itself with signal, and both are safe (handleInterrupt in src/main/main.c). Its SIGUSR1 and SIGUSR2 handlers, which save the workspace and quit, do not, and a comment above them in src/main/errors.c says so: “These do far more processing than is allowed in a signal handler”.

Masking signals

A process can block signals temporarily. While a handler runs, the kernel blocks the signal that triggered it, unless the handler was installed with SA_NODEFER, and the handler’s sa_mask in sigaction can block more signals for the same span. Outside handlers, sigprocmask (or pthread_sigmask in a threaded program) blocks signals around a critical section. A signal that arrives while blocked stays pending until it is unblocked.

Blocking signals is not the same as ignoring them. Blocked signals are delivered later. Ignored signals are discarded.

The SIGCHLD signal

When a child process exits, the kernel sends SIGCHLD to the parent. The default action is to ignore it. But a parent that wants to know when children exit can install a handler.

The handler does not receive the exit status directly. The handler must call waitpid() with the WNOHANG flag to collect the exit status without blocking.

void handle_sigchld(int sig) {
  int status;
  while (waitpid(-1, &status, WNOHANG) > 0) {
    // child exited, status is available
  }
}

Multiple children can exit before the handler is called. The handler must loop and collect all of them.

11.5.3 Ctrl-C and user interruption

When a user presses Ctrl-C in a terminal, the terminal driver sends SIGINT to the foreground process group. All processes in that group receive the signal. By default, SIGINT terminates the process.

An R session installs its own SIGINT handler. When the user presses Ctrl-C, R’s handler runs and sets an interrupt flag. At its next check point R sees the flag and signals an interrupt condition. An interrupt is not an error: tryCatch(expr, error = ...) does not catch it, and tryCatch(expr, interrupt = ...) does.

R checks the flag in many places. The evaluator checks about every thousand calls to eval, the bytecode interpreter about every thousand jumps, calls or loop iterations, and many of R’s own C loops check too: the arithmetic loops check every ten million elements (src/main/eval.c, src/main/arithmetic.c). Compiled code in a package is checked only when its author calls R_CheckUserInterrupt(), which “Writing R Extensions” asks for in long computations, or when the code calls back into R, for example through Rf_eval. Until such a check runs, the Ctrl-C waits.

A long BLAS call is the common case. A large matrix product can run for seconds inside the BLAS library, which never calls back into R, so the interrupt waits until the routine returns.

11.5.4 Signals in forked workers

When a parent process forks, the child inherits the signal handlers. A signal sent to the parent’s process ID reaches only the parent. A signal sent to a process group, which is what the terminal does on Ctrl-C, reaches every process in the group, and a forked child stays in its parent’s group unless it moves itself with setpgid.

A common pattern is that the parent handles Ctrl-C and cancels all workers. If the workers are forked children, they can inherit a handler that communicates with the parent or sets their own flag.

But signal handlers in forked children carry two hazards at once. A handler must already avoid locks, and a forked child may hold locked mutexes that a parent thread had taken when the fork happened.

The safer pattern is to have workers not handle signals. The parent catches Ctrl-C, sets a flag, and checks the flag periodically to decide when to cancel workers.

11.5.5 R and signals

GNU R handles SIGINT by setting the flag R_interrupts_pending (src/main/main.c). R_CheckUserInterrupt() tests the flag and, when it is set, signals an R condition of class interrupt (src/main/errors.c). The evaluator makes that check about every thousand evaluation steps, not only between top-level expressions.

Compiled code that never calls R_CheckUserInterrupt(), such as a BLAS routine, cannot be interrupted midway and must finish first.

On Unix-alikes R also installs handlers for SIGSEGV, SIGILL and SIGBUS, which print a message such as *** caught segfault *** and a traceback. A segfault still ends the session, with one exception: when R recognizes the segfault as a C stack overflow, it prints Error: segfault from C stack overflow and returns to the top level. R also handles SIGPIPE, SIGUSR1 and SIGUSR2.

Forked workers inherit R’s SIGINT handler. If a user presses Ctrl-C, the terminal sends SIGINT to the entire process group. Both parent and workers receive it, both run R’s handler, and both see an interrupt.

Coordinating cancellation across workers is hard. If the parent receives Ctrl-C, it needs to cancel all workers, and it cannot count on the terminal’s signal reaching them. The parent must send each worker a signal or use a shared flag. mclapply() does the first: when it is interrupted, it sends SIGTERM to the children it forked (its mc.cleanup argument, TRUE by default).

11.5.6 Cleanup and finally blocks

When an interrupt cancels R code, R unwinds the stack to the nearest handler for the interrupt, or to the top level, and functions registered with on.exit() run on the way.

In C code, R_CheckUserInterrupt() may not return when an interrupt is pending. It jumps straight into R’s condition handling, as “Writing R Extensions” warns, so C code must not hold resources that only its own exit path would free.

A second Ctrl-C can arrive during cleanup, for example while an on.exit() handler writes a file, and interrupt the cleanup code itself. suspendInterrupts() exists for that case: it holds interrupts off until the expression it wraps has finished.

11.5.7 Signals in other systems

Unix systems define signals as the standard mechanism for asynchronous notification. The POSIX standard defines the signal API.

Windows has no POSIX signals. Its C runtime emulates a few, but Microsoft’s documentation states that SIGINT is not supported for Win32 applications: on Ctrl-C, Windows starts a new thread to handle the interrupt. A console program registers that handler with SetConsoleCtrlHandler. R does this on Windows, and its handler records the interrupt in a flag, UserBreak (and raises an emulated SIGBREAK), which R picks up at its next interrupt check (src/gnuwin32/psignal.c).

11.5.8 Tradeoffs

Signals are asynchronous and interrupt code unpredictably. They are useful for Ctrl-C and other user interactions. But they are dangerous to use for application logic because of the safety constraints.

Dedicated cancellation mechanisms are safer. A flag that the code checks explicitly is more predictable than a signal that interrupts at any moment. On Unix, though, signals are the only way the OS delivers such interrupts to a process.

Further reading

  • signal(7) <https://man7.org/linux/man-pages/man7/signal.7.html>, sigaction(2) <https://man7.org/linux/man-pages/man2/sigaction.2.html> and signal-safety(7) <https://man7.org/linux/man-pages/man7/signal-safety.7.html> manual pages.
  • The Open Group, POSIX.1-2017 section 2.4.3, Signal Actions <https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04_03>, which lists the async-signal-safe functions.
  • Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces <https://pages.cs.wisc.edu/~remzi/OSTEP/>. Free online. The chapter “Interlude: Process API” introduces kill() and signals briefly.
  • Stevens, W. R. and Rago, S. A. (2013). Advanced Programming in the UNIX Environment, 3rd edition <https://www.pearson.com/en-us/subject-catalog/p/advanced-programming-in-the-unix-environment/P200000000628/9780321638007>. Addison-Wesley. Chapter 10 covers signals.
  • Microsoft, signal in the C runtime reference <https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/signal>, on how Ctrl-C works in Win32 programs.
  • R Core Team, “Writing R Extensions”, section Allowing interrupts <https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Allowing-interrupts>.

Where to go next

Back to top