Java: Kill all subprocesses on unix

2019-08-15 12:54发布

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条回答
疯言疯语
2楼-- · 2019-08-15 13:24

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.

查看更多
登录 后发表回答