杀死Java中进程的正确方法 [英] The right way to kill a process in Java
问题描述
杀死Java进程的最佳方法是什么?
What's the best way to kill a process in Java ?
获取PID,然后使用Runtime.exec()
将其杀死?
Get the PID and then killing it with Runtime.exec()
?
使用destroyForcibly()
吗?
这两种方法有什么区别,还有其他解决方案吗?
What's the difference between these two methods, and is there any others solutions ?
推荐答案
如果您要终止的进程已由您的应用程序启动
然后您可能会有一个引用(ProcessBuilder.start()
或Runtime.exec()
都返回一个引用).在这种情况下,您可以简单地调用p.destroy()
.我认为这是最干净的方法(但请注意:由p
启动的子进程可能仍然存在,请检查 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092 了解更多信息).
Then you probably have a reference to it (ProcessBuilder.start()
or Runtime.exec()
both return a reference). In this case, you can simply call p.destroy()
. I think this is the cleanest way (but be careful: sub-processes started by p
may stay alive, check http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092 for more info).
仅当在一定的超时后destroy()
失败时,才应使用destroyForcibly
.简而言之
The destroyForcibly
should only be used if destroy()
failed after a certain timeout. In a nutshell
- 使用
destroy()
终止程序 - 允许进程在合理的超时时间内正常退出 如果进程为
- 使用
destroyForcibly()
杀死它 还活着
- terminate process with
destroy()
- allow process to exit gracefully with reasonable timeout
- kill it with
destroyForcibly()
if process is still alive
如果您要终止的进程是外部的
然后您没有太多选择:您需要通过OS API(Runtime.exec
).在Windows上,要调用的程序为taskkill.exe
,而在Mac和Linux上,您可以尝试kill
.
Then you don't have much choice: you need to pass through the OS API (Runtime.exec
). On Windows, the program to call will be taskkill.exe
, while on Mac and Linux you can try kill
.
看看 https://github.com/zeroturnaround/zt-exec/issues/19 和使用Java杀死进程和 http://invisiblecomputer. wonderhowto.com/how-to/code-simple-java-app-kill-any-process-after-specified-time-0133513/了解更多信息.
Have a look at https://github.com/zeroturnaround/zt-exec/issues/19 and Killing a process using Java and http://invisiblecomputer.wonderhowto.com/how-to/code-simple-java-app-kill-any-process-after-specified-time-0133513/ for more info.
这篇关于杀死Java中进程的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!