问题
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