Java :杀死由 Runtime.getRuntime().exec() 运行的进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18047531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java :Kill process runned by Runtime.getRuntime().exec()
提问by user2646434
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
- 运行 unix 进程
Runtime.getRuntime().exec("java -jar MyServerRunner -port MYPORT");
- 通过从java代码执行命令找到进程的PID
lsof -t -i: MYPORT
- 并通过pid杀死他
kill -9 PID
(也通过从java代码执行命令) - 然后执行其他命令
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.
如果我通过Runtime.getRuntime().exec()
程序退出执行此命令,退出代码为 137 - 这意味着当我运行时,Runtime.getRuntime().exec("kill -9 PID")
我杀死了我的 java 程序的进程,而不是我从代码运行的程序。
How can I kill ONLY the process that I run from code ?
我怎样才能只杀死我从代码运行的进程?
P.S. maybe I should use ProcessBuilder ?
PS 也许我应该使用 ProcessBuilder ?
回答by assylias
You can kill a sub-process that you have launched from your java application with destroy
:
您可以使用以下命令终止从 Java 应用程序启动的子进程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.
另请注意,在单独的线程中而不是在单独的进程中运行其他代码可能更有意义。
回答by Hsin-Hsiang
you can use .exec("ps|grep <your process name>");
, and then parse the result to get the PID, finally .exec("kill PID");
可以使用.exec("ps|grep <your process name>");
,然后解析结果得到PID,最后.exec("kill PID");
Therefore, your process is killed but android app still alive.
因此,您的进程已被终止,但 android 应用程序仍然存在。
回答by rdemirkoparan
You can get pid with reflection in unix (I know it is a bad idea :)) and call kill;
您可以在 unix 中通过反射获取 pid(我知道这是一个坏主意:))并调用 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));