TExcelTAD
Home › Operating Systems: Linux & Windows › Signals & Console Events

Signals & Console Events

Sometimes a process must be told something right now, whatever it is doing: the user pressed Ctrl+C, the terminal was closed, a child exited, the system is shutting down. Unix solves this with signals, small numbered notifications the kernel delivers asynchronously. Windows has no signals in the kernel; instead it has a handful of mechanisms that cover the same situations: console control events, window messages, service control requests and TerminateProcess.

Signals on Linux

A signal is just a number (1–31 for the classic ones, 34–64 for real-time signals). When it arrives, the process does one of three things:

  1. the default action: terminate, terminate with a core dump, ignore, stop or continue;
  2. ignore it (SIG_IGN);
  3. run a handler function it registered with sigaction(), then resume where it was interrupted.

SIGKILL and SIGSTOP cannot be caught, blocked or ignored, so the kernel always keeps a way to stop a process.

Signal No. Default Typical cause
SIGHUP 1 terminate Terminal closed; daemons reload config
SIGINT 2 terminate Ctrl+C in the terminal
SIGQUIT 3 core dump Ctrl+\
SIGKILL 9 terminate (uncatchable) kill -9, the OOM killer
SIGSEGV 11 core dump Invalid memory access
SIGPIPE 13 terminate Writing to a pipe nobody reads
SIGTERM 15 terminate Polite "please exit" (kill, systemctl stop)
SIGCHLD 17 ignore A child exited or stopped
SIGCONT 18 continue fg, bg
SIGSTOP / SIGTSTP 19 / 20 stop Uncatchable stop / Ctrl+Z
bash · try it yourself
kill -l 2 9 15 17
kill -l | head -2
INT
KILL
TERM
CHLD
 1) SIGHUP	 2) SIGINT	 3) SIGQUIT	 4) SIGILL	 5) SIGTRAP
 6) SIGABRT	 7) SIGBUS	 8) SIGFPE	 9) SIGKILL	10) SIGUSR1

Some signals come from the kernel itself, as the result of what the process did: SIGSEGV for a bad pointer, SIGFPE for integer division by zero, SIGPIPE for writing into a closed pipe. Others come from other processes via the kill() system call, or from the terminal driver when you press a key.

Catching signals in bash

The shell's trap builtin registers a handler. A script can even send a signal to itself with kill and the special parameter $ (its own PID, used here but never printed):

bash · try it yourself
trap 'echo "caught SIGTERM, cleaning up"' TERM
trap 'echo "caught SIGUSR1: reloading config"' USR1
kill -TERM $
kill -USR1 $
echo "still running after both signals"
trap - TERM                    # restore the default action
trap -p                        # list remaining traps
caught SIGTERM, cleaning up
caught SIGUSR1: reloading config
still running after both signals
trap -- 'echo "caught SIGUSR1: reloading config"' SIGUSR1

The pseudo-signal EXIT runs when the script ends, however it ends: the standard place for cleanup.

bash · try it yourself
workdir=$(mktemp -d)
trap 'rm -rf "$workdir"; echo "removed the temporary directory"' EXIT
echo "data" > "$workdir/part1"
ls "$workdir"
echo "work finished"
part1
work finished
removed the temporary directory

A process killed by a signal reports exit status 128 + signal number to its parent. Here a background sleep is stopped (T), continued and then terminated:

bash · try it yourself
sleep 30 &
kill -STOP %1; sleep 0.2
echo "after SIGSTOP: state $(ps -o stat= -p $!)"
kill -CONT %1; sleep 0.2
echo "after SIGCONT: state $(ps -o stat= -p $!)"
kill -TERM %1
wait %1
echo "exit status $? = 128 + $(( $? - 128 )) ($(kill -l $(( $? - 128 ))))"
after SIGSTOP: state T
after SIGCONT: state S
exit status 143 = 128 + 15 (TERM)

Note: Signal handlers interrupt the program at an arbitrary instruction, so a C handler may only call async-signal-safe functions (write, _exit, not printf or malloc). The usual pattern is to set a flag and let the main loop act on it, or to use signalfd() and treat signals as readable events.

How the kernel delivers a signal

text
 sender: kill(pid, SIGTERM)          target process
          |                         +---------------------------------+
          v                         | pending mask:  ...0100000000... |
   kernel marks the signal  ------> | blocked mask:  ...0000000000... |
   pending in the target            +---------------------------------+
                                       | next return from kernel mode
                                       v
                     handler installed?  -- yes --> run handler on user stack, then sigreturn()
                                       | no
                                       v
                                 default action (terminate / core / stop / ignore)

Signals are checked when a thread returns from kernel to user mode (after a system call or interrupt), which is why delivery is fast but asynchronous. A blocked system call such as read() is interrupted and either restarted or fails with EINTR.

Windows: console control events

A console program on Windows receives control events from the console host instead of signals. It registers a handler with SetConsoleCtrlHandler(); Windows runs that handler on a new thread in the process (not by interrupting an existing one, as Unix does).

Event Cause Rough Unix equivalent
CTRL_C_EVENT Ctrl+C SIGINT
CTRL_BREAK_EVENT Ctrl+Break SIGQUIT
CTRL_CLOSE_EVENT Console window closed SIGHUP
CTRL_LOGOFF_EVENT / CTRL_SHUTDOWN_EVENT User logs off / system shuts down (services only) SIGTERM at shutdown

GUI programs get window messages instead: WM_CLOSE (the X button, taskkill without /f), WM_QUERYENDSESSION and WM_ENDSESSION at log-off. Services get SERVICE_CONTROL_STOP from the Service Control Manager. A batch file interrupted by Ctrl+C asks "Terminate batch job (Y/N)?".

The C runtime emulates a few signals with signal() (SIGINT, SIGTERM, SIGSEGV, SIGABRT, SIGFPE, SIGILL), but only inside the process: there is no kill() to send SIGTERM to another process. Hardware faults are delivered as structured exceptions (EXCEPTION_ACCESS_VIOLATION, 0xC0000005), the counterpart of SIGSEGV.

Stopping a process: kill vs taskkill

Linux's polite-then-forceful pattern is kill PID (SIGTERM), wait, then kill -9 PID. Windows' equivalent is taskkill without and with /f (sample output — yours will differ):

cmd
C:\Users\ada>taskkill /im notepad.exe
SUCCESS: Sent termination signal to the process "notepad.exe" with PID 14212.

C:\Users\ada>taskkill /f /pid 9920
SUCCESS: The process with PID 9920 has been terminated.
powershell
PS C:\Users\ada> Stop-Process -Name notepad            # forceful, like taskkill /f
PS C:\Users\ada> (Get-Process notepad).CloseMainWindow() # polite: sends WM_CLOSE
True

Without /f, taskkill posts WM_CLOSE to the program's windows, so it may show "Save changes?". With /f (and with Stop-Process), Windows calls TerminateProcess(): the process is ended immediately, no handler runs and no cleanup happens, just like SIGKILL.

Task Linux Windows
Ask a process to exit kill PID (SIGTERM) taskkill /pid N (WM_CLOSE), CloseMainWindow()
Force it kill -9 PID taskkill /f, Stop-Process, TerminateProcess()
Interrupt from keyboard Ctrl+C → SIGINT Ctrl+C → CTRL_C_EVENT
Pause / resume kill -STOP / -CONT Resource Monitor "Suspend process", NtSuspendProcess
Notify parent of child exit SIGCHLD Wait on the process handle (it becomes signalled)
Catch in code sigaction(), trap SetConsoleCtrlHandler(), [Console]::CancelKeyPress

Learn more: Processes · Inter-Process Communication · ps, kill & top

Test yourself

Which two Linux signals can never be caught or ignored?

  1. SIGINT and SIGTERM
  2. SIGKILL and SIGSTOP
  3. SIGHUP and SIGQUIT
  4. SIGSEGV and SIGPIPE

How does Windows deliver Ctrl+C to a console program that registered a handler?

  1. By interrupting the main thread like a Unix signal
  2. As a SIGINT through kill()
  3. By running the handler on a new thread in the process
  4. Through a registry key

A process was killed by SIGTERM (15). What exit status does the shell report?

  1. 15
  2. 1
  3. 143
  4. -15