更新時間:2022-08-02 10:00:17 來源:動力節(jié)點 瀏覽1467次
Java結(jié)束進(jìn)程的流程是什么?動力節(jié)點小編來告訴大家。java1.8之后,Process有了destroy和destroyForcibly方法,用來結(jié)束進(jìn)程,一般結(jié)束進(jìn)程的流程為:
terminate process with destroy()
allow process to exit gracefully with reasonable timeout
kill it with destroyForcibly() if process is still alive
但是在java1.8的實現(xiàn)中,下面是源碼:
public Process destroyForcibly(){
destroy();
return this;
}
可以看到destroyForcibly和destroy是等效的,這樣就有一個問題,如果一段時間后destroy無法關(guān)閉進(jìn)程,那么destroyForcibly又怎么能保證能強(qiáng)制關(guān)閉進(jìn)程呢?除此之外,如果新進(jìn)程又開啟了一個新的子進(jìn)程,又如何關(guān)閉新的子進(jìn)程呢?(雖然這是新進(jìn)程的責(zé)任,但是在'強(qiáng)制關(guān)閉'的情況下,新進(jìn)程應(yīng)該無法保證能順利的關(guān)閉子進(jìn)程)。
在java9+中,Process有了一個新的方法:toHandle,可以獲取到 ProcessHandle對象,這個對象也有 destroy和destroyForcibly這兩個方法,看了下它們的實現(xiàn),是一個native方法
private static native boolean destroy0(long pid, long startTime, boolean forcibly);
應(yīng)該比Process的更加可靠,至少強(qiáng)制關(guān)閉看起來不再是自欺欺人,而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.
這個方法可以獲取進(jìn)程的直接子進(jìn)程,通過
p.children().forEach(ProcessHandle::destroy);
可以關(guān)閉它的直接子進(jìn)程。如果這還不夠,還有一個descendants方法,可以返回直接子進(jìn)程以及子進(jìn)程的子進(jìn)程。
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);
應(yīng)該是更好的關(guān)閉方法。
初級 202925
初級 203221
初級 202629
初級 203743