Sunday, February 1, 2009

Kill a specific program in linux

Particulary while you are in development few program behave weirdly and you wanna kill them anyway.
Generally what ppl does is do a ps or ps aux to list of all the programs then search for the particulary program by looking at the whole list or just by doing at
ps aux | grep 'gedit' (in this case the pgm is gedit) and then they give a ps or if they want a force kill instead of a grace full kill they give
ps -9

Here i give a simple snippet to do the same in one shot
kill `ps aux | grep gedit | grep -v 'grep' | awk '{print $2}'`

The logic is very simple here, we are searching the ps listing (ps aux) for the gedit records (grep gedit) and then remove the 'grep gedit' row (grep -v 'gedit') and then extract the pid (awk '{print $2}') . The final step would be give the extracted pid to the kill command (using the ``).
You may want to use the -9 for a force kill.

An other good option would be to use pkill but the problem with that would be that it would kill all instances of the specified program.
pkill
eg: pkill firefox
You customize the above simple code snippet to find out exactly the one program you want to retreive and kill it.
You can save this as a command if you are using it again and again.

No comments: