11

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

Joachim Sauer
  • 291,719
  • 55
  • 540
  • 600
Mike
  • 302
  • 6
  • 18

2 Answers2

20

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

Petar Minchev
  • 45,963
  • 11
  • 102
  • 118
  • 2
    add /F flag so that it kills SYSTEM processes too. – Denis Tulskiy Jan 08 '11 at 12:08
  • 4
    As I remember, taskkill.exe is only available on Windows XP Professional and later (not in the Home Edition). You might consider shipping the code with something like pskill, just in case: http://technet.microsoft.com/en-en/sysinternals/bb896683.aspx –  Jan 08 '11 at 12:26
  • @Hypnos Shipping your app with pskill is dangerous because many virus scanners detect pskill as "dangerous application" for an unknown reason. – Robert Jan 08 '11 at 13:08
  • add /T flag so that if the process is a 16 bit and launched into the ntvdm wow system, that too will be killed. Otherwise it might still run even though the launching script has been killed. – The Coordinator Mar 23 '15 at 08:40
1

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.

Xavier Guihot
  • 43,847
  • 17
  • 251
  • 159