Java: Kill all subprocesses on unix

对着背影说爱祢 提交于 2019-12-11 09:14:19

问题


I got an application written in java which runs on Unix and starts two sub-processes (via Runtime.getRuntime().exec()) on startup. If the application crashed for some reason, the sub processes won't get killed.

Now, I added a shutdown hook which gets fired on every crash, ok so far. But I'd like to send a SIGTERM signal (or at least SIGINT) on UNIX console for every sub process of the application. I should be able to find their process IDs via ps, but I did not make it to extract the PID correctly and send a signal for every process.

Can anyone help?

Thank you very much!


回答1:


What I'm suggesting it is not an official feature, but a tricks.

This is how I get process id for my java applications. I never found another way.

public static final String getPid() {
    try {
        RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
        String name = runtimeBean.getName();
        int k = name.indexOf('@');
        if (k > 0)
            return name.substring(0, k);
    } catch (Exception ex) {
    }
    return null;
}

This works on win, mac and linux.



来源:https://stackoverflow.com/questions/10052383/java-kill-all-subprocesses-on-unix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!