Java :Kill process runned by Runtime.getRuntime().exec()

javaprocessunix

I need to write a code,that

  1. run unix process with Runtime.getRuntime().exec("java -jar MyServerRunner -port MYPORT");
  2. find PID of the process by executing command from java code lsof -t -i: MYPORT
  3. and kill him by pid kill -9 PID ( also by executing command from java code)
  4. and then execute others commands

BUT

if I execute this command by Runtime.getRuntime().exec() my program exits with exit code 137 – this means that when I run Runtime.getRuntime().exec("kill -9 PID") I kill process of My java programm, but not the program, that I run from code.

How can I kill ONLY the process that I run from code ?

P.S. maybe I should use ProcessBuilder ?

Best Answer

You can kill a sub-process that you have launched from your java application with destroy:

Process p = Runtime.getRuntime().exec("java -jar MyServerRunner -port MYPORT");
p.destroy();

Also note that it might make sense to run that other code in a separate thread rather than in a separate process.