Java 版本 9 以后,Java 提出了可以查询和终止主进程及其后代的功能。查询子进程的代码片段
import java.io.IOException;
public class ProcessTreeTest {
public static void main(String args[]) throws IOException {
Runtime.getRuntime().exec("cmd");
System.out.println("Showing children processes:");
ProcessHandle processHandle = ProcessHandle.current();
processHandle.children().forEach(childProcess ->
System.out.println("PID: " + childProcess.pid() + " Command: " + childProcess.info().command().get()));
System.out.println("Showing descendant processes:");
processHandle.descendants().forEach(descendantProcess ->
System.out.println("PID: " + descendantProcess.pid() + " Command: " + descendantProcess.info().command().get()));
}
}
为了杀死进程及其子进程,Java9 有 API 遍历所有children
进程并调用destroy
它们中的每一个
例如:在您的情况下,您从 apache-commons 获取 Process 对象,然后尝试以下代码
Process child = ...;
kill (child.toHandle());
public void kill (ProcessHandle handle)
{
handle.descendants().forEach((child) -> kill(child));
handle.destroy();
}
参考 :
https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html
https://www.tutorialspoint.com/how-to-traverse-a-process-tree-of-process-api-in-java-9
如何从 Java 终止进程树?
注意 - 我还没有尝试过这个功能,只是阅读了关于 Java9 并发现在这里分享很有帮助。