How do I kill a specific process from Java code on Windows, if I have the specific PID.
I don't know any other solution, apart from executing a specific Windows
command like Runtime.getRuntime().exec("taskkill /F /PID 827");
With Java 9
, we can use ProcessHandle:
ProcessHandle.of(11395).ifPresent(ProcessHandle::destroy);
where 11395
is the pid
of the process you're interested in killing.
This:
First creates an Optional<ProcessHandle>
from the given pid
And if this ProcessHandle
is present, kills the process using destroy
.
No import necessary as ProcessHandle
is part of java.lang
.
To force-kill the process, one might prefer ProcessHandle::destroyForcibly
to ProcessHandle::destroy
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With