Monday, December 24, 2007

Kill java processes from perl script

Requirement:- If multiple java processes are running on your system and you want to kill only few specific from them.
If we do it manually then we have to perform below two steps:

1. jps (it will return all the java processes running on the system) in below format:
<pid>     <process name>
<pid>     <process name>
<pid>     <process name>
<pid>     <process name>
...

in my case i got the below output from above command:

1234 Server1
1334 Server2
1454 Server3
1264 Server4
1238 Server5
1244 Server6

2. now i have the process id of all the java processes so i can kill them using kill command, (let say if i have to kill only Server1, Server5 , then)

kill -9 1234
kill -9 1238

By using perl script, i can write below simple script which will do my above task:

foreach $_ (`jps`) {
my($pid,$pname) = /(\S+)\s+(.*)/;
if($pname eq "Server1" | $pname eq "Server5" ) {
print("Killing Process : $pname ($pid) \n");
system("kill -9 $pid");
}
}

No comments: