当我的Java应用程序退出/崩溃时,如何摆脱Java子进程? [英] How do I get rid of Java child processes when my Java app exits/crashes?
问题描述
我使用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问题中所述)
一些标准库有自己的钩子,可以在你的之前运行。
some of the standard libraries have their own hooks which may run before yours.
小心死锁。
另一种可能性是将您的java程序包装在服务中。
这篇关于当我的Java应用程序退出/崩溃时,如何摆脱Java子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!