I would like to know how to \"kill\" a process that has started up. I am aware of the Process API, but I am not sure, If I can use that to \"kill\" an already running proces
With Java 9
, we can use ProcessHandle which makes it easier to identify and control native processes:
ProcessHandle
.allProcesses()
.filter(p -> p.info().commandLine().map(c -> c.contains("firefox")).orElse(false))
.findFirst()
.ifPresent(ProcessHandle::destroy)
where "firefox" is the process to kill.
This:
First lists all processes running on the system as a Stream
Lazily filters this stream to only keep processes whose launched command line contains "firefox". Both commandLine
or command
can be used depending on how we want to retrieve the process.
Finds the first filtered process meeting the filtering condition.
And if at least one process' command line contained "firefox", then kills it using destroy
.
No import necessary as ProcessHandle
is part of java.lang
.