当我的 Java 应用程序退出/崩溃时,如何摆脱 Java 子进程? [英] How do I get rid of Java child processes when my Java app exits/crashes?

查看:24
本文介绍了当我的 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 程序包装在一个服务中.

这篇关于当我的 Java 应用程序退出/崩溃时,如何摆脱 Java 子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆