Reputation: 63
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.
Upvotes: 0
Views: 1163
Reputation: 308081
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
Upvotes: 2