I need to write a code,that
Runtime.getRuntime().exec("java -jar MyServerRunner -port MYPORT");
lsof -t -i: MYPORT
kill -9 PID
( also by executing command from java code)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 ?
In Java, the Runtime class is used to interact with Every Java application that has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method.
exit() The System. exit() method stops the running Java Virtual Machine.
Kill command. This command is used to kill processes by its PID( or process id). By default, it will send a "SIGTERM" signal that we have discussed above. However, this command can be used to kill multiple processes with a single command.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With