Bash - Kill a process
Table of Contents
1 - About
How to kill a process
2 - Articles Related
3 - Utility
3.1 - kill
kill is bash builtin command
kill [-s sigspec | -n signum | -sigspec] [pid | jobspec] ...
kill -l [sigspec | exit_status]
Send the signal named by sigspec or signum to the processes named by pid or jobspec. sigspec is either a case-insensitive signal name such as SIGKILL (with or without the SIG prefix) or a signal number; signum is a signal number. If sigspec is not present, then SIGTERM is assumed. An argument of -l lists the signal names. If any arguments are supplied when -l is given, the names of the signals corresponding to the arguments are listed, and the return status is 0. The exit_status argument to -l is a number specifying either a signal number or the exit status of a process terminated by a signal. kill returns true if at least one signal was successfully sent, or false if an error occurs or an invalid option is encountered.
3.2 - pkill
pkill will look up or signal processes based on name and other attributes
Syntax
pkill [-signal] [-fvx] [-n|-o] [-P ppid,...] [-g pgrp,...]
[-s sid,...] [-u euid,...] [-U uid,...] [-G gid,...]
[-t term,...] [pattern]
where:
- - f The full command line is used to match a process with the pattern (Default: process name)
4 - Example
4.1 - SIGKILL handler
########### SIGKILL handler ############
function _kill() {
echo "SIGKILL received, shutting down database!"
}
4.2 - Kill.sh
#!/bin/sh
get_pid ()
{
os_name=`uname -s`
case "$os_name" in
SunOS)
ANA_VARIANT="Solaris";;
HP-UX)
ANA_VARIANT="HPUX";;
AIX)
ANA_VARIANT="AIX";;
Linux)
ANA_VARIANT="Linux";;
CYGWIN_NT-5.*)
ANA_VARIANT="Windows";;
*)
ANA_VARIANT="UnknownOS"
esac
if [ "$ANA_VARIANT" = "AIX" ]; then
echo `ps -u$LOGNAME | grep $1 | awk '{print $2}'`
else
echo `ps -u$LOGNAME | grep $1 | awk '{print $1}'`
fi
}
pid=`get_pid $1`
if test "$pid" ; then
echo "Killing $1"
kill -9 $pid
fi
exit 0
where pid is the process id
4.3 - Wait a little bit before killing
wait_until_done ()
{
pid=$1
cnt=${DRILLBIT_TIMEOUT:-300}
origcnt=$cnt
while kill -0 $pid > /dev/null 2>&1; do
if [ $cnt -gt 1 ]; then
cnt=`expr $cnt - 1`
sleep 1
else
echo "Process did not complete after $origcnt seconds, killing."
kill -9 $pid
exit 1
fi
done
return 0
}