Java: Kill process executed by Runtime.getRuntime (). Exec ()

I need to write code that

  • start the unix process with Runtime.getRuntime().exec("java -jar MyServerRunner -port MYPORT");
  • find the PID of the process by running the command from the java code lsof -t -i: MYPORT
  • and kill it pid kill -9 PID (also by running a command from java code)
  • and then execute other commands

BUT

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

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

PS maybe i should use ProcessBuilder?

+6
source share
3 answers

You can kill the subprocess that you started from your java application using destroy :

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

Also note that it makes sense to run this other code in a separate thread, rather than in a separate process.

+10
source

you can use .exec("ps|grep <your process name>"); and then analyze the result to get the PID, finally .exec("kill PID");

So your process is dead, but the Android app is still alive.

+1
source

You can get a pid with reflection in unix (I know this is a bad idea :)) and call kill;

 Process proc = Runtime.getRuntime().exec( new String[] {"java","-classpath",System.getProperty("java.class.path"),... }); Class<?> cProcessImpl = proc.getClass(); Field fPid = cProcessImpl.getDeclaredField("pid"); if (!fPid.isAccessible()) { fPid.setAccessible(true); } Runtime.getRuntime().exec("kill -9 " + fPid.getInt(proc)); 
0
source

Source: https://habr.com/ru/post/951005/


All Articles