Killing a process using Java

前端 未结 8 1812
名媛妹妹
名媛妹妹 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();
    

提交回复
热议问题