简体   繁体   English

当我的 Java 应用程序退出/崩溃时,如何摆脱 Java 子进程?

[英]How do I get rid of Java child processes when my Java app exits/crashes?

I launch a child process in Java as follows:我在 Java 中启动了一个子进程,如下所示:

final String[] cmd = {"<childProcessName>"};
Process process = Runtime.getRuntime().exec(cmd);

It now runs in the background.它现在在后台运行。 All good and fine.一切都很好。

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?当父 Java 进程死亡时,如何使其自动结束?

If it helps, I'm using Mac OS X 10.5如果有帮助,我使用的是 Mac OS X 10.5

I worked it out myself already.我已经自己解决了。 I add a shutdown hook, as follows:我添加了一个关闭钩子,如下:

final String[] cmd = {"<childProcessName>"};
final Process process = Runtime.getRuntime().exec(cmd);
Runnable runnable = new Runnable() {
    public void run() {
        process.destroy();
    }
};
Runtime.getRuntime().addShutdownHook(new Thread(runnable));

As you said, addShutdownHook is the way to go.正如你所说, addShutdownHook是要走的路。

BUT:但:

  • There's no real guarantee that your shutdown hooks are executed if the program terminates.如果程序终止,并不能真正保证您的关闭挂钩会被执行。 Someone could kill the Java process and in that case your shutdown hook will not be executed.有人可能会杀死 Java 进程,在这种情况下,您的关闭挂钩将不会执行。 (as said in this SO question ) (如this SO question所述)

  • some of the standard libraries have their own hooks which may run before yours.一些标准库有它们自己的钩子,它们可能在你的之前运行。

  • beware of deadlocks.谨防死锁。

Another possibility would be to wrap your java program in a service .另一种可能性是将您的 java 程序包装在一个服务中

Adding shutdown hook is not a reliable method to kill the child processes.添加关闭钩子不是杀死子进程的可靠方法。 This is because Shutdown hook might not necessarily be executed when a force kill is performed from Task Manager.这是因为从任务管理器执行强制终止时,不一定会执行关闭挂钩。

One approach would be that the child process can periodically monitor the PID of its parent.一种方法是子进程可以定期监视其父进程的 PID。 This way, Child process can exit itself when the parent exits.这样子进程可以在父进程退出时自行退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM