Monday, November 30, 2009

Killing a process in linux

As a software enthusiast one thing I have to do several times is killing a process, some people will term it as ugly or bad, but general software developers often come across situation where killing a process is handy or necessary. I will mention some use cases later in the blog.Killing a process usually involves 2 steps. Finding the process ID that is intended to be terminated and terminating it with a kill statement. Step one for general users (like myself) again involves a ps command with some grepping and then manual lookup. I have to do these almost every time I kill a process. I have simply put this steps into the following script so that I can do them in a single command.
#!/bin/bash
if [ -z $3 ]; then
USER_STR=`whoami`
else
USER_STR=$3
fi
echo User: $USER_STR
process_str=`ps -eopid,user,cmd grep $USER_STR grep $1 grep $2`
pid=`echo $process_str cut -d' ' -f0-1`
if [ -z $pid ]; then
pid=`echo $process_str cut -d' ' -f1-2`
if [ -z $pid ]; then
pid=`echo $process_str cut -d' ' -f2-3`
if [ -z $pid ]; then
pid=`echo $process_str cut -d' ' -f3-4`
else
echo "Retrieved PID: " $pid
fi
else
echo "Retrieved PID: " $pid
fi
else
echo "Retrieved PID: " $pid
fi
if [ -z $pid ]; then
echo 'Could not execute kill. PID: ' $pid
else
kill -9 $pid
fi

If someone has any improvements please inform me about it.The shell script expects 3 arguments, of which 2 are mandatory and 1 is optional. The first 2 are grep params to identify the process. For example, to identify a Tomcat running Escenic Content Engine I use java and escenic.root to identify the process. The third param is the user to search it with. If it is not provided then whoami will be used to determine the user executing the shell.This shell script has enabled me to sync, build, deploy my projects all with a single command and this helps me save some sustainable amount of time. Now without a build server I can still achieve what a build server like Hudson can do. Actually I use this script from within Hudson and thus I almost "never" have to be concerned about deploying applications to my demo server. I hope this is useful to all

No comments:

Post a Comment