当我的 Java 应用程序退出/崩溃时,如何摆脱 Java 子进程?
我在 Java 中启动一个子进程如下:
I launch a child process in Java as follows:
final String[] cmd = {"<childProcessName>"};
Process process = Runtime.getRuntime().exec(cmd);
它现在在后台运行.一切都很好.
It now runs in the background. All good and fine.
如果我的程序现在崩溃了(它是仍在开发中:-))子进程似乎仍然徘徊.当父 Java 进程死亡时,如何使其自动结束?
If my program now crashes (it is still in dev :-)) the child process still seems to hang around. How can I make it automatically end when the parent Java process dies?
如果有帮助,我使用的是 Mac OS X 10.5
If it helps, I'm using Mac OS X 10.5
推荐答案
如你所说,addShutdownHook 是要走的路.
As you said, addShutdownHook is the way to go.
但是:
如果程序终止,并不能真正保证您的关闭挂钩会被执行.有人可能会杀死 Java 进程,在这种情况下,您的关闭挂钩将不会被执行.(如本 SO question 中所述)
一些标准库有自己的钩子,可能在你之前运行.
some of the standard libraries have their own hooks which may run before yours.
小心死锁.
另一种可能性是将您的 java 程序包装在一个服务中.
相关文章