Monday, October 13, 2008

Terminating Processes Containing Given Pattern

Generally, if you want to terminate a process which contains the given pattern, you use following 4 steps:

  1. $ ps aux | grep pattern 
  2. Copy the pid of the process from output of above command.
  3. Paste this pid in the following command
  4. $ kill -9 pid

The above procedure is cumbersome and requires much typing.

Therefore I have written a program to terminate process(es), which contains given pattern. (I am assuming that ~/bin is in your $PATH).

$ vi ~/bin/kill_prog.sh

#!/bin/sh

# Kills the program given


if [ $# -lt 2 ]
then
  echo "Usage: $0 [1/0] signal program-name"
  echo "[0/1] Do not Kill / Do kill (optional)"
  echo "signal -TERM (Graceful Terminate), -KILL (Abrupt KIll)"
  exit
fi

donothing=1
signal=$1
program=$2
if [ $# -gt 2 ]
then
  donothing=$1
  signal=$2
  program=$3
fi

pids=$(ps auxww | awk "/ $program / { print \$2 }")


for pid in $pids
do
  if [ $donothing -eq 1 ] ; then
  echo "kill $signal $pid"
  else
  kill $signal $pid
  fi
done

#end kill_prog.sh

By default, this program does not kills the process. You have to

pass 0 as second parameter to the command to kill.

Sample runs of above programs:

$ kill_prog.sh
Usage: /home/mitesh/Programming/Shell/WCS/kill_prog.sh [1/0] signal program-name
[0/1] Do not Kill / Do kill (optional)
signal -TERM (Graceful Terminate), -KILL (Abrupt KIll)

$ kill_prog.sh -TERM ping
kill -TERM 16050
$ kill_prog.sh -KILL ping
kill -KILL 16050
$ kill_prog.sh 1 -KILL ping
kill -KILL 16050
$ kill_prog.sh 0 -KILL ping
Killed

The last command actually terminates(-TERM) or kills(-TERM).

No comments: