Killing a process using Java

前端 未结 8 1728
名媛妹妹
名媛妹妹 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 12:03

    You can kill a (SIGTERM) a windows process that was started from Java by calling the destroy method on the Process object. You can also kill any child Processes (since Java 9).

    The following code starts a batch file, waits for ten seconds then kills all sub-processes and finally kills the batch process itself.

    ProcessBuilder pb = new ProcessBuilder("cmd /c my_script.bat"));
    Process p = pb.start();
    p.waitFor(10, TimeUnit.SECONDS);
    
    p.descendants().forEach(ph -> {
        ph.destroy();
    });
    
    p.destroy();
    
    0 讨论(0)
  • 2020-11-22 12:07

    Try it:

    String command = "killall <your_proccess>";
    Process p = Runtime.getRuntime().exec(command);
    p.destroy();
    

    if the process is still alive, add:

    p.destroyForcibly();
    
    0 讨论(0)
提交回复
热议问题