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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:56:20  来源:igfitidea点击:

How to kill a process in Java, given a specific PID

javawindows

提问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 Windowscommand 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 11395is the pidof the process you're interested in killing.

这里11395pid你感兴趣的杀人过程。

This:

这个:

  • First creates an Optional<ProcessHandle>from the given pid

  • And if this ProcessHandleis present, kills the process using destroy.

  • 首先Optional<ProcessHandle>从给定的创建一个pid

  • 如果ProcessHandle存在,则使用destroy.

No import necessary as ProcessHandleis part of java.lang.

不需要导入,因为它ProcessHandlejava.lang.

To force-kill the process, one might prefer ProcessHandle::destroyForciblyto ProcessHandle::destroy.

要强制杀死进程,人们可能更喜欢ProcessHandle::destroyForciblyProcessHandle::destroy