Java:杀死Unix上的所有子进程 [英] Java: Kill all subprocesses on unix
问题描述
我有一个用Java编写的应用程序,该应用程序可在Unix上运行,并在启动时启动两个子进程(通过Runtime.getRuntime().exec()
).如果应用程序由于某种原因而崩溃,则子进程将不会被杀死.
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.
现在,我添加了一个关闭钩子,到目前为止,每次崩溃都会触发该钩子.但是我想在UNIX控制台上为应用程序的每个子进程发送一个SIGTERM信号(或者至少是SIGINT).我应该能够通过ps
找到他们的进程ID,但是我没有正确地提取PID并为每个进程发送信号.
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.
任何人都可以帮忙吗?
非常感谢!
推荐答案
我建议的不是官方功能,而是技巧.
What I'm suggesting it is not an official feature, but a tricks.
这是我获取Java应用程序的进程ID的方式.我再也找不到其他方法了.
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;
}
这适用于Win,Mac和Linux.
This works on win, mac and linux.
这篇关于Java:杀死Unix上的所有子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!