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

后端 未结 3 821
既然无缘
既然无缘 2020-12-10 12:23

I launch a child process in Java as follows:

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


        
相关标签:
3条回答
  • 2020-12-10 12:53

    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. This way, Child process can exit itself when the parent exits.

    0 讨论(0)
  • 2020-12-10 12:57

    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));
    
    0 讨论(0)
  • 2020-12-10 13:17

    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.

    0 讨论(0)
提交回复
热议问题