发表于 2018-09-05 09:26
java1.8之后,Process
有了destroy
和destroyForcibly
方法,用来结束进程,一般结束进程的流程为:
但是在java1.8的实现中,下面是源码:
public Process destroyForcibly() {
destroy();
return this;
}
可以看到destroyForcibly
和destroy
是等效的,这样就有一个问题,如果一段时间后destroy
无法关闭进程,那么destroyForcibly
又怎么能保证能强制关闭进程呢?除此之外,如果新进程又开启了一个新的子进程,又如何关闭新的子进程呢?(虽然这是新进程的责任,但是在’强制关闭’的情况下,新进程应该无法保证能顺利的关闭子进程)。
在java9+中,Process
有了一个新的方法:toHandle
,可以获取到 ProcessHandle
对象,这个对象也有 destroy
和destroyForcibly
这两个方法,看了下它们的实现,是一个native方法
private static native boolean destroy0(long pid, long startTime, boolean forcibly);
应该比Process
的更加可靠,至少强制关闭看起来不再是自欺欺人,而ProcessHandle
还提供了一个children
方法:
Returns a snapshot of the current direct children of the process.The parent of a direct child process is the process.Typically, a process that is not alive has no children.
这个方法可以获取进程的直接子进程,通过
p.children().forEach(ProcessHandle::destroy);
可以关闭它的直接子进程。如果这还不够,还有一个descendants
方法,可以返回直接子进程以及子进程的子进程。
Returns a snapshot of the descendants of the process.The descendants of a process are the children of the processplus the descendants of those children, recursively.Typically, a process that is not alive has no children.
所以java9以及以后
ProcessHandle handle = p.toHandle();
handle.destroy();
handle.descendants().forEach(ProcessHandle::destroy);
应该是更好的关闭方法