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

跟風遠走 提交于 2019-11-27 23:28:34

问题


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.

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?

If it helps, I'm using Mac OS X 10.5


回答1:


As you said, addShutdownHook is the way to go.

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. (as said in 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.




回答2:


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));


来源:https://stackoverflow.com/questions/261125/how-do-i-get-rid-of-java-child-processes-when-my-java-app-exits-crashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!