Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

windows

How do I kill a specific process from Java code on Windows, if I have the specific PID.

like image 254
Mike Avatar asked Jan 08 '11 11:01

Mike


2 Answers

I don't know any other solution, apart from executing a specific Windows command like Runtime.getRuntime().exec("taskkill /F /PID 827");

like image 102
Petar Minchev Avatar answered Sep 21 '22 03:09

Petar Minchev


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.

like image 43
Xavier Guihot Avatar answered Sep 23 '22 03:09

Xavier Guihot