Useless use of kill -9

Killing from Scripts | Signals

The -9 (or -KILL) argument to kill(1) should never be used on Unix systems, except as a very last resort. The KILL signal does not allow a process to run any cleanup code, which means blasting away with kill -9 may leave child processes of a parent orphaned, temporary files open, shared memory segments active, and sockets busy. This leaves the system in a messy state, and could lead to unanticipated and hard to debug problems.

$ kill -9 1435

Instead, use the proper TERM signal by default, and only work up to a KILL if less problematic signals prove insufficient. Automating the following commands is covered in a subsequent section.

$ 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. However, using the KILL signal by default assumes the problematic process will remain so. A safer approach is to instead script a series of kill signals: always start with a standard TERM signal, and work up to KILL only if necessary.

If KILL does not cause a process to exit, then the process is most likely involved with the Unix kernel somehow. Good luck!

Killing from Scripts

Using a Bourne-based shell such as bash or zsh, escalating kill calls can be automated. The following cycle_kill function is used in the script reallykill.

cycle_kill () {
PID=$1
RETVAL=0

for signal in "TERM" "INT" "HUP" "KILL"; do
kill -$signal $PID
RETVAL=$?
[ $RETVAL -eq 0 ] && break
echo "warning: kill failed: pid=$PID, signal=$signal" >&2
sleep 1
done

return $RETVAL
}

cycle_kill 1435

Example use of reallykill, where a HUP is sufficient to exit the process:

$ kill 1435
$ reallykill 1435
warning: kill failed: pid=1435, signal=TERM
warning: kill failed: pid=1435, signal=INT

Or in Perl, use something like:

for my $signal (qw{TERM INT HUP KILL}) {
last if kill $signal, $pid;
warn "warning: kill failed: pid=$pid, signal=$signal\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 a list of signals supported on the system in question.