[comp.unix.shell] Killing process

timr@hpwarcz.wal.hp.com (Tim Rice) (05/14/91)

I have a ksh script I've been toying with that'll kill a named set of
processes.
In my case it'll be built up into a startup script but others may want to
modify it to pass in the process name from the command line.

I've attached it and was wondering if anyone has any easier/better ways
of doing
this?

-Tim

************************************************************************
***********
cut here
#!/bin/ksh
#
# Script to kill all named processes in pass function

# Usage:  killem [-signumber]

#
# pass() --
#    get list of processes to kill during the pass.
# 
function pass
{
    pids=`/bin/ps -ef`

    for pid in $pids; do 
	case $pid in
	  xrn|xcalc)
	    pidk=`/bin/ps -ef | grep $pid | /bin/sed            \
		-e '/^[ ]* .* .*grep/d'                         \
	 	-e 's/^[ ]*[^ ]\{1,8\}[ ]*\([0-9]\{1,5\}\).*/\1/'`
	    echo $pidk
	    ;;
	  *)
	    ;;
	esac
    done
}

#
# Get the signal number specified [if any, defaults to -9]
#
signo="${1#-}"
signo=${signo:-9}

if [ $# -gt 1 -o $signo -lt 0 -o $signo -gt 31 ]; then
    echo "Usage: killem [ -signo ]" >&2
    exit 2
fi

#
# If no signal was specified, use signal 15 to let things die
# gracefully before we send the real signal.
# We sleep for a while too, to give everyone a chance to die.
#
if [ $# -eq 0 ]; then
    kill -15 `pass` >/dev/null 2>&1
    sleep 3
fi

#
# Now kill with the real signal.  We warn with the "second pass"
# processes with a SIGTERM before actually killing them with SIGKILL.
# We sleep for a while too, to give everyone a chance to die.
#
kill -$signo `pass` >/dev/null 2>&1
sleep 3

exit 0