Killing a process using Java

前端 未结 8 1744
名媛妹妹
名媛妹妹 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:52

    Accidentally i stumbled upon another way to do a force kill on Unix (for those who use Weblogic). This is cheaper and more elegant than running /bin/kill -9 via Runtime.exec().

    import weblogic.nodemanager.util.Platform;
    import weblogic.nodemanager.util.ProcessControl;
    ...
    ProcessControl pctl = Platform.getProcessControl();
    pctl.killProcess(pid);
    

    And if you struggle to get the pid, you can use reflection on java.lang.UNIXProcess, e.g.:

    Process proc = Runtime.getRuntime().exec(cmdarray, envp);
    if (proc instanceof UNIXProcess) {
        Field f = proc.getClass().getDeclaredField("pid");
        f.setAccessible(true);
        int pid = f.get(proc);
    }
    

提交回复
热议问题