Search code examples
javaprocesscross-platform

How can I kill a process from a Java application, if I know the PID of this process? I am looking for a cross-platfrom solution


I know there are several ways to kill a process from Java, but all of these use some kind of platform-specific code that only works on Windows or Linux.

Is there a lib I can use where I can just call something like

Process.kill(pid);

Or perhaps there is a method that I can write that handles (almost) all cases of OS?

All I want to do is terminate a process, knowing it's PID already.


Solution

  • Since Java 9 there's ProcessHandle which allows interaction with all processes on a system (constrained by system permissions of course).

    Specifically ProcessHandle.of(knownPid) will return the ProcessHandle for a given PID (technically an Optional which may be empty if no process was found) and destroy or destroyForcibly will attempt to kill the process.

    I.e.

    long pid = getThePidViaSomeWay();
    Optional<ProcessHandle> maybePh = ProcessHandle.of(pid);
    ProcessHandle ph = maybePh.orElseThrow(); // replace with  your preferred way to handle no process being found.
    ph.destroy(); //or
    ph.destroyForcibly(); // if you want to be more "forcible" about it