Sending Signals with kill
A signal is a short notification that the kernel delivers to a process. It carries no data, only a number, and it interrupts whatever the process is doing. Some signals ask a process to stop, some pause or resume it, and some have no fixed meaning and are used by programs for their own purposes, such as "reload your configuration". kill is the command that sends signals.
The name is historical: the default signal ends the process, so the command was called kill, but kill can send any signal. kill -STOP pauses a process, kill -CONT resumes it, and kill -0 sends nothing at all and only checks that the process exists.
This lesson covers the kill command, the signals scripts use most, how to address processes, jobs and process groups, and what the exit status of a signalled process looks like. Lesson 141 covers the receiving side in depth: how a script handles interrupts and termination requests with trap.
The Basic Form
kill [-s SIGNAL | -n NUMBER | -SIGNAL] PID | %JOB ...
kill -l [SIGNAL | STATUS]
Without a signal option, kill sends SIGTERM (signal 15), a polite request to terminate:
sleep 30 & p=$!
kill "$p"
wait "$p"; echo "status $? = $(kill -l $?)"
status 143 = TERM
The status 143 is 128 + 15, the convention for "ended by signal 15" (lesson 116). kill -l with a number above 128 subtracts 128 and prints the signal name.
Built-in and External kill
kill exists twice on most systems:
type -a kill
kill is a shell builtin
kill is /usr/bin/kill
kill is /bin/kill
The Bash built-in is used unless you type a path. It understands job specifications such as %1, and it keeps working when the system cannot start new processes (for example, when a runaway script has used up the process limit), because it runs inside the shell. The external /bin/kill from util-linux has a few extra options, but in scripts the built-in is the normal choice. All examples here use the built-in.
Naming Signals
Every signal has a number and a name. kill -l lists them; the first lines on Linux are:
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
kill -l also converts in both directions:
kill -l 15
kill -l TERM
kill -l SIGKILL
kill -l 137
TERM
15
9
KILL
All of the following send SIGKILL; each run ended a sleep with status 137:
kill -9 "$p"
kill -KILL "$p"
kill -SIGKILL "$p"
kill -s KILL "$p"
kill -s SIGKILL "$p"
kill -n 9 "$p"
Names are preferred over numbers. The numbers of the common signals 1, 2, 3, 9 and 15 are the same everywhere, but others differ between systems: SIGUSR1 is 10 on Linux and 30 on macOS. -s NAME is the POSIX form; -NAME is shorter and widely supported.
The Signals Scripts Use Most
| Signal | Number | Default action | Typical meaning |
|---|---|---|---|
| SIGHUP | 1 | terminate | terminal closed; many services use it as "reload configuration" |
| SIGINT | 2 | terminate | interrupt; sent by Ctrl + C |
| SIGQUIT | 3 | terminate with core dump | quit; sent by Ctrl + \ |
| SIGKILL | 9 | terminate | forced kill; cannot be caught or ignored |
| SIGUSR1, SIGUSR2 | 10, 12 | terminate | user-defined; the program decides what they mean |
| SIGTERM | 15 | terminate | polite request to terminate; the default of kill |
| SIGCONT | 18 | continue | resume a stopped process |
| SIGSTOP | 19 | stop | pause; cannot be caught or ignored |
| SIGTSTP | 20 | stop | pause request; sent by Ctrl + Z |
(Numbers are for Linux on x86 and ARM.) The column "default action" is what happens when the process has not arranged anything else. A program, including a Bash script with trap, can replace the default action for every signal except SIGKILL and SIGSTOP.
How a Process Reacts
A small script shows the three possible reactions. It handles HUP and USR1 by printing a message and continuing, and handles TERM by exiting cleanly:
# target.sh
trap 'echo "target: got HUP (reload config)"' HUP
trap 'echo "target: got USR1 (print status)"' USR1
trap 'echo "target: got TERM, exiting"; exit 0' TERM
echo "target $$ ready"
while :; do sleep 1 & wait $!; done
bash target.sh & t=$!
sleep 0.3
kill -HUP "$t"; sleep 0.2
kill -USR1 "$t"; sleep 0.2
kill -TERM "$t"; wait "$t"; echo "target exit status $?"
bash target.sh & t=$!
sleep 0.3
kill -KILL "$t"; wait "$t"; echo "after SIGKILL: $?"
target 1336 ready
target: got HUP (reload config)
target: got USR1 (print status)
target: got TERM, exiting
target exit status 0
target 1343 ready
c.sh: line 8: 1343 Killed bash target.sh
after SIGKILL: 137
- HUP and USR1 ran their handlers, and the script kept going.
- TERM ran its handler, which chose to exit with status 0. Because the script handled the signal, its exit status is whatever the handler chose, not 143.
- KILL bypassed the script completely: no handler ran, and the status was 137. Bash, as the parent, printed the
Killedline.trap '...' KILLis accepted without an error (status 0) but never runs, as lesson 123 also found.
This is why SIGTERM should be the first choice. It gives the process a chance to finish what it is doing: remove temporary files, write buffered data, close connections. SIGKILL ends the process immediately, in the middle of whatever it was doing, and should be a last resort for processes that ignore SIGTERM.
Pausing and Resuming: STOP and CONT
SIGSTOP freezes a process, and SIGCONT lets it continue. ps shows a stopped process with the state T:
sleep 30 & p=$!; sleep 0.1
kill -STOP "$p"; sleep 0.1; ps -o pid=,stat=,args= -p "$p"
kill -CONT "$p"; sleep 0.1; ps -o pid=,stat=,args= -p "$p"
1106 T sleep 30
1106 S sleep 30
S means sleeping, the normal state of a process that is waiting for something. This is the same mechanism that Ctrl + Z, fg and bg use (lesson 137), applied to any process by PID. It can be used to pause a heavy background job temporarily, for example while you need the CPU or the disk for something else.
The sleep 0.1 before kill -STOP matters. In a first version of this test, the signal arrived so quickly after & that it stopped the forked shell before it had started sleep, and ps showed bash a.sh instead of sleep 30.
Checking a Process with kill -0
Signal number 0 is not a real signal. kill -0 PID performs every check that sending a signal would, but sends nothing, and its exit status answers the question "does this process exist, and may I signal it?":
sleep 30 & p=$!
kill -0 "$p"; echo "alive: $?"
kill "$p"; wait "$p"
kill -0 "$p"; echo "after end: $?"
alive: 0
a.sh: line 12: kill: (1091) - No such process
after end: 1
Add 2>/dev/null when you only want the status. Lesson 139 used kill -0 to check a PID file and to wait for a process that was not a child of the script.
Which Processes Can Be Signalled
An ordinary user can signal only their own processes. The root user can signal any process. A process owned by root, signalled by the user nobody:
sleep 30 & p=$! # started by root
setpriv --reuid=nobody --regid=nogroup --clear-groups \
bash -c "kill $p; echo \"as nobody: status \$?\"; kill -0 $p; echo \"kill -0 as nobody: \$?\""
bash: line 1: kill: (1112) - Operation not permitted
as nobody: status 1
bash: line 1: kill: (1112) - Operation not permitted
kill -0 as nobody: 1
Note that kill -0 also returned 1, although the process exists. When the exact reason matters, ps -p PID tells whether the process exists regardless of who owns it; the complete example below uses it.
Errors and Exit Status
kill returns 0 if it sent at least one signal successfully, and 1 otherwise. Invalid usage returns 2:
kill 999999; echo "status $?"
kill -BOGUS 1; echo "status $?"
kill abc; echo "status $?"
kill; echo "status $?"
a.sh: line 15: kill: (999999) - No such process
status 1
a.sh: line 16: kill: BOGUS: invalid signal specification
status 1
a.sh: line 18: kill: abc: arguments must be process or job IDs
status 1
kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
status 2
With several PIDs, kill signals each one it can and reports the others, but the status is 0 as long as one succeeded:
sleep 30 & a=$!; sleep 30 & b=$!
kill "$a" 999999 "$b"; echo "status $?"
a.sh: line 21: kill: (999999) - No such process
status 0
Both sleep processes received SIGTERM (wait returned 143 for each). A script that needs to know about every PID should call kill once per PID, as the complete example does.
Addressing Jobs and Process Groups
Job Specifications
In addition to PIDs, the built-in kill accepts job specifications: kill %1 signals job 1, kill %+ the current job (lesson 137). This works in interactive shells and in scripts.
Process Groups
A negative number addresses a whole process group (lesson 135): kill -- -1371 sends SIGTERM to every process whose process group ID is 1371. The -- marks the end of the options; without it, kill reads -1371 as a signal number:
sleep 30 & kill -$!
h.sh: line 1: kill: 1366: invalid signal specification
Process groups solve the problem from lesson 139: killing the PID of a { ...; } & group only ends the subshell, not the commands it started. With set -m, every background job gets its own process group whose ID equals $!, so the whole job can be ended at once:
set -m # each job gets its own process group
{ sleep 30 & sleep 30 & wait; } &
job=$!
sleep 0.3
ps -eo pid=,ppid=,pgid=,args= | awk -v g="$job" '$3 == g'
kill -- "-$job" # negative number: the whole group
sleep 0.2
echo "processes left in group $job: $(pgrep -g "$job" -r R,S | wc -l)"
wait
1371 1369 1371 bash g.sh
1373 1371 1371 sleep 30
1374 1371 1371 sleep 30
[1]+ Terminated { sleep 30 & sleep 30 & wait; }
processes left in group 1371: 0
The subshell (1371) and both sleep processes shared process group 1371, and one kill ended all three. The Terminated line is printed because job control is on. The same script without set -m, killing only $job, left both sleep processes running. (pgrep -r R,S counts only running and sleeping processes, so ended processes that their parent has not yet collected are not counted.)
Be careful with negative numbers. kill -- -1 is special: it sends the signal to every process the user is allowed to signal, which for root means nearly every process on the system.
By Name: pkill and pgrep
pgrep and pkill (from the procps package, not part of Bash) find processes by name or command line:
sleep 41 & sleep 42 & sleep 0.1
pgrep -f 'sleep 4[12]' | wc -l
pkill -f 'sleep 41'; echo "pkill status $?"
pkill -f 'sleep 99'; echo "pkill no match: $?"
2
pkill status 0
pkill no match: 1
-f matches against the full command line; without it, only the process name is matched, and -x requires an exact name. pkill takes the same signal options as kill (pkill -HUP nginx). Matching by name is convenient but imprecise: it can hit other users' processes (when run as root) or unrelated programs with similar names. Always try the pattern with pgrep -a first, which lists what would be matched. In scripts, a saved PID (lesson 139) is safer.
A Complete Example: Stop Gracefully, Then Force
stop.sh implements the usual escalation: send SIGTERM to each process, give them time to finish, and send SIGKILL only to those still running after a timeout.
#!/usr/bin/env bash
# stop.sh [-t SECONDS] PID...: ask each process to stop with SIGTERM,
# and use SIGKILL only for those still running after SECONDS (default 5).
set -uo pipefail
prog=${0##*/}
timeout=5
if [[ ${1-} == -t ]]; then timeout=${2-}; shift; shift; fi
[[ $timeout =~ ^[0-9]+$ ]] || { echo "$prog: -t needs whole seconds" >&2; exit 2; }
(( $# > 0 )) || { echo "usage: $prog [-t SECONDS] PID..." >&2; exit 2; }
alive() { kill -0 "$1" 2>/dev/null; }
now_ms() { local t=${EPOCHREALTIME/./}; echo $(( t / 1000 )); } # Bash 5.0+
pending=() status=0
for pid in "$@"; do
if [[ ! $pid =~ ^[1-9][0-9]*$ ]]; then
echo "$prog: not a PID: $pid" >&2; status=1; continue
fi
if kill -TERM "$pid" 2>/dev/null; then
echo "$pid: sent SIGTERM"
pending+=("$pid")
elif ps -p "$pid" > /dev/null; then # exists, but kill was refused
echo "$prog: $pid: permission denied" >&2; status=1
else
echo "$prog: $pid: no such process" >&2; status=1
fi
done
deadline=$(( $(now_ms) + timeout * 1000 ))
while (( ${#pending[@]} > 0 && $(now_ms) < deadline )); do
sleep 0.2
still=()
for pid in "${pending[@]}"; do
if alive "$pid"; then still+=("$pid"); else echo "$pid: stopped"; fi
done
pending=("${still[@]}")
done
for pid in "${pending[@]}"; do # ignored SIGTERM: force it
kill -KILL "$pid" 2>/dev/null && echo "$pid: did not stop after ${timeout}s, sent SIGKILL"
done
exit "$status"
How It Works
- Validation: the regular expression
^[1-9][0-9]*$accepts only positive numbers. This rejects text, and it also rejects0and negative numbers, whichkillwould interpret as process groups, including the dangerous-1. - One
killper PID gives a separate result for each process. Whenkill -TERMfails,ps -pdecides between "permission denied" (the process exists) and "no such process";kill -0cannot make that distinction, as shown above. - The polling loop checks every 0.2 seconds which processes are still alive and removes the ones that have ended. The deadline uses milliseconds from
EPOCHREALTIME. An earlier version used Bash's whole-secondSECONDScounter, and with-t 2it gave up after only 1.2 seconds in one test, because the counter could advance shortly after the deadline was computed. - Escalation: any PID still in
pendingafter the deadline receives SIGKILL. The script cannot usewait, because the processes are usually not its children.
Running the Complete Example
Three test processes were started from a script: polite.sh, which needs half a second to clean up after SIGTERM; stubborn.sh, which ignores SIGTERM; and a plain sleep 30:
# polite.sh
trap 'echo "polite $$: cleaning up"; sleep 0.5; exit 0' TERM
while :; do sleep 1 & wait $!; done
# stubborn.sh
trap 'echo "stubborn $$: ignoring SIGTERM"' TERM
while :; do sleep 1 & wait $!; done
bash polite.sh & p1=$!
bash stubborn.sh & p2=$!
sleep 30 & p3=$!
sleep 0.3
echo "polite=$p1 stubborn=$p2 sleep=$p3"
TIMEFORMAT='took %1Rs'
time bash stop.sh -t 2 "$p1" "$p2" "$p3" 999999 abc; echo "stop.sh status $?"
wait "$p1"; echo "polite: $?"
wait "$p2"; echo "stubborn: $? ($(kill -l $?))"
wait "$p3"; echo "sleep: $? ($(kill -l $?))"
polite=1294 stubborn=1295 sleep=1296
1294: sent SIGTERM
stubborn 1295: ignoring SIGTERM
polite 1294: cleaning up
1295: sent SIGTERM
1296: sent SIGTERM
stop.sh: 999999: no such process
stop.sh: not a PID: abc
1296: stopped
1294: stopped
1295: did not stop after 2s, sent SIGKILL
run.sh: line 7: 1295 Killed bash stubborn.sh
took 2.0s
stop.sh status 1
polite: 0
stubborn: 137 (KILL)
sleep: 143 (TERM)
The lines from the test processes and from stop.sh are interleaved because they run at the same time; the order changed between runs. The results are consistent: the plain sleep ended at once with the default action of SIGTERM (status 143); polite.sh cleaned up and exited with its own status 0; stubborn.sh survived SIGTERM and was ended by SIGKILL after the 2-second timeout (status 137). The invalid arguments made stop.sh exit with status 1.
Run as the user nobody against a sleep owned by root, the permission check reported the refused signal (the script was read from standard input, so $0 was bash):
bash: 1176: permission denied
bash: 999999: no such process
Missing PIDs (bash stop.sh) and a non-numeric timeout (-t x) are rejected with status 2.