4

In my java program I want to kill a process named "DummyBroker"(which is another java program). i could kill it using TaskKill but it needs PID of the process. So how can i fetch the pid for a specific java process and then kill it?

zer0Id0l
  • 1,374
  • 4
  • 22
  • 36
  • `tasklist` will print all processes formatted. You can use this output to search for the right process and fetch its PID. Note that this only works in Windows, but I guess you're aware. – Steffen Mar 24 '14 at 13:58
  • Related: http://stackoverflow.com/questions/35842/how-can-a-java-program-get-its-own-process-id – Sandeep Chatterjee Mar 24 '14 at 14:01
  • As a short term work around i have created a static `Process`. Start the java app using `runtime.exec` and kill the process using `p.destroy` – zer0Id0l Mar 24 '14 at 15:27

4 Answers4

7

You should take a look at this link : Killing a process using Java

And use something like :

Runtime.getRuntime().exec("taskkill /F /IM <processname>.<extension>")

Otherwise you can maybe use a combinaison of tasklistand split to find the containing line and then find the PID.

Jason C
  • 38,729
  • 14
  • 126
  • 182
Clad Clad
  • 2,653
  • 1
  • 20
  • 32
  • 2
    This can only kill by taskname. All java programs have java.exe as the taskname – Roberto Anić Banić Mar 24 '14 at 14:08
  • The java process will be named as "java.exe", above command will kill all the java process not the specific java application(in my case 'com.xxx.java.broker.DummyBroker') – zer0Id0l Mar 24 '14 at 14:33
  • 1
    I can't try it now because I am on a mac, but I will try to give you a more specify way to do it tonight if no one gives you an answer meanwhile ;) – Clad Clad Mar 24 '14 at 14:34
4

Finally found a easy solution here

jps - Java Virtual Machine Process Status Tool , can be used for killing a java process with its name.

for /f "tokens=1" %i in ('C:\java\jdk-7u45-windows-x64\bin\jps -m ^| find "DummyBroker"') do ( taskkill /F /PID %i )

We can add above in batch file and simply call the batch file from java program.

zer0Id0l
  • 1,374
  • 4
  • 22
  • 36
2
Runtime.getRuntime().exec("taskkill /F /IM " + TASKNAME);

Though this only kills by taskname

cruisepandey
  • 28,520
  • 6
  • 20
  • 38
Roberto Anić Banić
  • 1,411
  • 10
  • 21
0

Go through this link...http://www.golesny.de/p/code/javagetpid

Use java.lang.management.ManagementFactory like this

RuntimeMXBean rtb = ManagementFactory.getRuntimeMXBean();
String processName = rtb.getName();
int result = 0;

Pattern pattern = Pattern.compile("^([0-9]+)@.+$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(processName);
if (matcher.matches()) {
result = new Integer(Integer.parseInt(matcher.group(1)));
}
Arjit
  • 3,290
  • 1
  • 17
  • 18