Useless use of kill -9

Discussion | Killing from Scripts | Signals | Related

Discussion

The unix KILL signal should only be used as a last resort. Too often, I see well-meaning people on unix systems using the -9 or -KILL argument to kill(1) by default. This is process assassination, and should never be done. Safe alternatives are explored below.

$ kill -9 1435

Process 1435 might be the parent for any number of child processes that will end up in limbo because the KILL signal does not give the parent a chance to inform any children. Additionally, the KILL signal prevents a process from cleaning up any temporary files and shared memory segments, or shutting down socket connections.

Instead, use the TERM signal by default, and work up to a KILL if the process in question proves resilient.

$ kill 1435
$ kill -INT 1435
$ kill -HUP 1435
$ kill -KILL 1435

Use of kill -9 by default may seem acceptable where a known problematic application is involved. That is, the application in question has not responded to anything but the KILL signal in the past. However, using the KILL signal by default assumes the problematic process will always be problematic. This assumption may cause problems in the future if the application is fixed. As a safe escalating kill cycle is trivial to script, there is no reason to use the KILL signal by default.

Killing from Scripts

Using a Bourne-based shell, the escalating kill signal concept can be written as follows. This code fragment is easily included in other scripts, or enhanced into a shell script to be used in place of kill. The KILL signal is only sent as the last resort.

# $PID needs to contain process number we want to kill
for signal in "TERM" "INT" "HUP" "KILL"; do
kill -$signal $PID
if [ $? -eq 0 ]; then
break
fi
echo "warning: kill -$signal $PID failed" >&2
sleep 1
done

The cycle is also easy to code in perl inside a loop.

# $pid needs to contain process number we want to kill
for my $signal (qw(TERM INT HUP KILL)) {
last if kill "$signal", $pid;
warn "warning: kill $signal $pid failed\n";
sleep 1;
}

Signals

Kill signals may be given either by name or by number. This means kill -1 and kill -HUP are equivalent. However, using the name of the signal is safer, as -1 may be mistyped or misinterpreted by the system, which may result in a signal being sent to the wrong process, such as init(8) if a command involving kill -1 was botched by a superuser.

For more information on kill signals, see kill(1) or run kill -l for the signals supported on the system in question.

Related