Linux commands
Browse topics

Sending signals with kill

Version
unversioned
Review
Draft

Summary#

kill sends a signal to a process. The default signal, TERM, asks it to terminate and can be handled; KILL cannot be caught or ignored.

Syntax#

sh
kill -TERM "$pid"
kill -KILL "$pid"
kill -0 "$pid"
kill -l 137

For a positive PID, signal 0 checks existence and permission without delivering a signal. A successful check can also find a zombie process.

Example#

The script signals only the worker processes that it starts.

sh
(
  set -eu
  dir=$(mktemp -d)
  worker=
  trap 'if [ -n "$worker" ]; then kill -KILL "$worker" 2>/dev/null || true; fi
    rm -rf -- "$dir"' EXIT

  for signal in TERM KILL; do
    rm -f -- "$dir/ready"
    sh -c 'trap "echo cleaning up; exit 0" TERM
      : > "$1"
      while :; do sleep 0.1; done' sh "$dir/ready" &
    worker=$!
    until [ -e "$dir/ready" ]; do sleep 0.1; done

    kill -0 "$worker"
    echo "sending $signal"
    kill -s "$signal" "$worker"
    status=0
    wait "$worker" 2>/dev/null || status=$?
    worker=
    echo "exit status $status"
  done
  kill -l 137
)

Expected output#

Text
sending TERM
cleaning up
exit status 0
sending KILL
exit status 137
KILL

Common mistakes#

Check that the PID belongs to the intended process before signaling it. A PID operand of 0 or less can signal multiple processes. Send TERM first and allow time to exit. KILL gives the process no chance to flush data, remove temporary files or stop its own children.

Version applicability#

The example uses the shell's built-in kill. Dash and Bash report 137 from wait for a child killed by SIGKILL. The number can differ in other shells. The separate kill program also varies by distribution.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0