Java :Kill process runned by Runtime.getRuntime().exec()
Solution 1
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.
Solution 2
You can get pid with reflection in unix (I know it 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));
Solution 3
you can use .exec("ps|grep <your process name>");
, and then parse the result to get the PID, finally .exec("kill PID");
Therefore, your process is killed but android app still alive.
user2646434
Updated on June 07, 2022Comments
-
user2646434 almost 2 years
I need to write a code,that
- run unix process with
Runtime.getRuntime().exec("java -jar MyServerRunner -port MYPORT");
- find PID of the process by executing command from java code
lsof -t -i: MYPORT
- and kill him by pid
kill -9 PID
( also by executing command from java code) - 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 runRuntime.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 ?
- run unix process with