Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill only processes (instances) of specific Java jar

I need to create automatic script, which kills running processes of specific Java JARs.

I do it manually like this:

jps -v

6753 Jps
4573 myJarToKill.jar
4574 notMyJarToKill.jar
4576 myJarToKill.jar

I pick up specific processes according JAR name for example myJarToKill.jar and run to kill them.

kill 4573 4576  

Is it possible to get numbers of this processes by grep or sth like this? A pass it to kill command?

like image 794
BlueJezza Avatar asked Jan 22 '16 08:01

BlueJezza


1 Answers

The command to use is a combination of grep, awk, and xargs unix command:

jps -v | grep "<your file name>" | grep -v "<if you need to exclude other output>" |awk '{print $<field number>}'|xargs kill -<kill signal>

Before to execute it please read the following explanation:

first of all run this: jps -v | grep "myJarToKill.jar" | awk '{print $1}'

Note: $2 means that the ps output is splitted in space separated field. So when you run the command for the first time please check that awk '{print $2}' output is the expected result otherwise you should change the field number $2 with the ones that you need.

if the "notMyJarToKill.jar" is still present add this:

jps -v  | grep "myJarToKill.jar" | grep -v "notMyJarToKill.jar"| awk '{print $1}' 

Then if the output result contains the pid that you would kill you can run this

jps -v  | grep "myJarToKill.jar" | awk '{print $1}'|xargs kill -9 

Note: you could also use kill -TERM it's depend by your needs.

Regards Claudio

like image 172
ClaudioM Avatar answered Sep 24 '22 23:09

ClaudioM