再java9及以上可以使用如下代码
ProcessHandle handle = p.toHandle();
handle.destroy();
handle.descendants().forEach(ProcessHandle::destroy);
杀死process的直接子进程和间接子进程
java8没有相关的方法,可以采取通过反射获取pid然后杀死进程树的方式杀死相关进程
代码如下,既能杀死sudo进程,又能杀死python进程
String cmd = “/usr/bin/sudo -u nobody /usr/bin/python3.6 ./test.py”;
try{
Process process = Runtime.getRuntime().exec(cmd);
System.out.println(process);
Field f =process.getClass().getDeclaredField(“pid”);
f.setAccessible(true);
long handl =f.getLong(process);
System.out.println(“handl:” + handl);
if (!process.waitFor(100, TimeUnit.SECONDS)) {
//process.destroyForcibly();
String cmd2 = "kill -SIGTERM " + String.valueOf(handl);
Process process2 = Runtime.getRuntime().exec(cmd2);
if (!process.waitFor(100, TimeUnit.SECONDS)) {
process2.destroyForcibly();
} else {
System.out.println(“kill success”);
}
throw new Exception(“exec Timeout”);
} else {
System.out.println(“exec success”);
}
Thread.sleep(20000L);
System.out.println(“hello”);
} catch(Exception e) {
throw e;
}

更多推荐

java中使用Process开启的子进程无法destroy的问题