0

I am wondering if we can stop a Single JVM within specific time limit. If it is not stopping within that time limit then kill the process from shell script.

If we are executing ./stopServer.sh JVM_Name - It will run till the jvm will not get stopped or till any error and exit.

What I am trying to do is :./stopServer.sh JVM_Name - If this do not stopped within 2 min(suppose), then kill the process (But How to figure out it is not stopped within 2 mins through shell script before the process go for killing). I can write the condition to kill . But not sure how to do checks if the JVM stopped within 2 mins or not so that we can go ahead to kill process.

Can anyone please suggest shell script code to identify if the jvm is stopped within specific time limit or not?

RonyA
  • 585
  • 3
  • 11
  • 26

1 Answers1

0

A JVM is a process and as such can be stopped with the kill command - kill $processid or more brutal kill -9 $processid

If you start the JVM from a script using something like java ... then I suggest putting a & at the end of that line and in the following line

processid=$!

which saves the id of the background process. Then

sleep 120

will wait for 2 min. Now you have two options - either just kill

kill $processid /dev/null 2>&1

or first check if the processid might (very unlikely) be reused by another process (or use some other way to check if your JVM has finished, maybe a file that indicates this from your java program) and then if it matches use the kill.

ps -ef|grep -w $processid |grep -w java > /dev/null

If it has returncode zero then continue with the kill

test $? -eq 0 && kill $processid

I usually would trust that the processid is either my JVM or not used at all

Stefan Hegny
  • 2,107
  • 4
  • 23
  • 26
  • Nice suggestion. I will be reaching office in next 1 hour. Will defintely do a check . – RonyA Jun 02 '16 at 07:06
  • I tried your suggestion . I got at one doubt. $! is capturing the pid after the command got executed . Suppose the pid captured from background is not available and the new process(orphans) left . How to tackel this situation.Is this good ./stopServer.sh JVM & > /somelocation ; sleep 120; PID=`ps -ef | grep $JVM| grep -v grep | awk '{print$2}'` ; if [[ "" != "$PID" ]] then kill -9 $PID fi – RonyA Jun 02 '16 at 09:44
  • hmm, from your websphere tag I had nearly anticipated that the thing that you start might not be the actual process that you would want to kill. so your stopServer.sh spawns a java and that does not terminate after 2 min? Maybe it has work to do while stopping? Have you checked IBM docs about that? – Stefan Hegny Jun 02 '16 at 09:51
  • Not yet . I can write it in while loop but need to check . – RonyA Jun 02 '16 at 09:53