windows 给定特定的 PID,如何在 Java 中终止进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4633678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to kill a process in Java, given a specific PID
提问by Mike
How do I kill a specific process from Java code on Windows, if I have the specific PID.
如果我有特定的 PID,如何在 Windows 上从 Java 代码中终止特定进程。
回答by Petar Minchev
I don't know any other solution, apart from executing a specific Windows
command like Runtime.getRuntime().exec("taskkill /F /PID 827");
除了执行Windows
像这样的特定命令之外,我不知道任何其他解决方案Runtime.getRuntime().exec("taskkill /F /PID 827");
回答by Xavier Guihot
With Java 9
, we can use ProcessHandle:
有了Java 9
,我们可以使用ProcessHandle:
ProcessHandle.of(11395).ifPresent(ProcessHandle::destroy);
where 11395
is the pid
of the process you're interested in killing.
这里11395
是pid
你感兴趣的杀人过程。
This:
这个:
First creates an
Optional<ProcessHandle>
from the givenpid
And if this
ProcessHandle
is present, kills the process usingdestroy
.
首先
Optional<ProcessHandle>
从给定的创建一个pid
如果
ProcessHandle
存在,则使用destroy
.
No import necessary as ProcessHandle
is part of java.lang
.
不需要导入,因为它ProcessHandle
是java.lang
.
To force-kill the process, one might prefer ProcessHandle::destroyForcibly
to ProcessHandle::destroy
.
要强制杀死进程,人们可能更喜欢ProcessHandle::destroyForcibly
到ProcessHandle::destroy
。