Sending Signals with kill

Su Suriya Ravichandran Updated 06 Dec 2026
14 min read ·Lesson 140 of 205

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

SignalNumberDefault actionTypical meaning
SIGHUP1terminateterminal closed; many services use it as "reload configuration"
SIGINT2terminateinterrupt; sent by Ctrl + C
SIGQUIT3terminate with core dumpquit; sent by Ctrl + \
SIGKILL9terminateforced kill; cannot be caught or ignored
SIGUSR1, SIGUSR210, 12terminateuser-defined; the program decides what they mean
SIGTERM15terminatepolite request to terminate; the default of kill
SIGCONT18continueresume a stopped process
SIGSTOP19stoppause; cannot be caught or ignored
SIGTSTP20stoppause 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 Killed line. trap '...' KILL is 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 rejects 0 and negative numbers, which kill would interpret as process groups, including the dangerous -1.
  • One kill per PID gives a separate result for each process. When kill -TERM fails, ps -p decides between "permission denied" (the process exists) and "no such process"; kill -0 cannot 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-second SECONDS counter, and with -t 2 it 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 pending after the deadline receives SIGKILL. The script cannot use wait, 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Sending Signals with kill and get answers drawn from it.

Signed-in readers only.