Killing a process using Java

前端 未结 8 1804
名媛妹妹
名媛妹妹 2020-11-22 11:08

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

8条回答
  •  攒了一身酷
    2020-11-22 11:54

    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.

提交回复
热议问题