Tuesday, March 25, 2008

How to kill running processes with multiple instances

I have my .bashrc file setup with many aliases, you can see more here. One of them is to kill processes, but sometimes it's not useful for running processes with multiple instances.

My alias looks like:

alias fproces='ps x | grep '

So when I get a process or an app that I want to kill I can do the following:

$ fproces gedit
7892 ? S 0:00 gedit
7894 pts/1 R+ 0:00 grep gedit
$ kill -9 7892

This is not that useful for applications/processes like Firefox:

$ fproces firefox
5994 ? S 0:00 /bin/sh /usr/bin/firefox
6006 ? S 0:00 /bin/sh /usr/lib/firefox/run-mozilla.sh /usr/lib/firefox/firefox-bin
6011 ? Sl 54:24 /usr/lib/firefox/firefox-bin
7898 pts/1 R+ 0:00 grep firefox
$ kill -9 5994 6006 6011

So I came up with a little script that does the following:

$ finish.sh
Enter app name
5994 ? S 0:00 /bin/sh /usr/bin/firefox
6006 ? S 0:00 /bin/sh /usr/lib/firefox/run-mozilla.sh /usr/lib/firefox/firefox-bin
6011 ? Sl 54:38 /usr/lib/firefox/firefox-bin

Do you want to kill all items? [y|n]

The script lists all processes related to the app and kill it if you say “y”. In this example I typed in “firefox” when prompted for an app name.

Here is what the script looks like:


## reads process name and assign it to var app
echo "Enter app name"
read app

## sets a minimum size for the var app. Without this, you could easily kill all running processes
minim=`echo "$app" | wc -m`

if [ "$minim" -lt "4" ] ; then
echo "Please try again with an app name"
exit 1

## looks for the running process instances, lists it and asks if you want to kill all of them
ps x | grep "$app" | grep -v 'grep'
echo "Do you want to kill all items? [y|n] "

## reads the answer and acts if it's an “y”
read resposta
if [ "$resposta" = "y" ] ; then
termina=`ps x | grep "$app" | grep -v 'grep' | awk '{print $1 ; }'`
for i in `echo $termina` ; do
kill -9 "$i"


1 comment:

Anonymous said...

I have to admit, that script is simple and works beautifully. 'pkill' or 'killall' just wasn't cutting it for me.