Wednesday, March 19, 2008

Linux Script for start and stop a specific process

This is script which I wrote to start and stop java program in rebhat linux. I think it should be run in any linux environment. I did not check that in other destro.

Start Script -

nohup nice java -cp ./:lib/mysql.jar:lib/activation.jar:lib/imap.jar:lib/mailapi.jar:lib/pop3.jar:lib/smtp.jar:./:bin KappaUserChecker > ./kappauc.out 2>&1 &

Stop Script -

kill `ps -ef | grep KappaUserChecker | grep -v grep | awk '{ print $2 }'`


nohup nice

nohup is a Unix command that is used to run another command while suppressing the action of the HUP (hangup) signal, enabling the command to keep running after the user who issues the command has logged out. It is most often used to run commands in background as daemons. Output that would normally go to the terminal goes to a file called nohup.out if it has not already been redirected.Nice allows you to run a program with a modified scheduling priority with -20 being most important and 20 being less important. I believe the default when using nice without a value is 0.

The '>' command

Takes the output from my java command and places it in the file ./kappauc.out

The '2>&1' command

2> is standard error and &1 is standard output. So combined it says take standard error and put it in standard output, which the previous command said take standard output and put it in
./kappauc.out. So together these two commands put standard output and error in ./kappauc.out.

The '&' command

When appending it at the end like it is, it means runs this process in the background.

Stop Script explained

Uses the Process Status (ps) command and grep to search for a process that includes the text 'hudson-1.136.war'. Then it uses awk to split out the output from ps to get the Process ID. Once the Process ID is found it passes it to the kill program to stop the daemon (pipes rock!). This method of using kill to stop a process is rather brute force and does have some flaws if you don't use unique text to search (multiple users running hundreds of programs). Most programs, say weblogic, for example should already have a stop script, so obviously prefer those over my example.

So what if you want the startup script to begin at boot time? Well, add a soft link pointing to your startup script  (ln -s /home/YourProject/bin/ in /etc/init.d/. Then use the update-rc.d command to add it at boot time (update-rc.d softlink_name defaults).

chamath gunasekara,

1 comment:

Marutha said...

This is really good one..but say for eg. i run your java application with multiple instances, how do I close as specific one?