Java – How to cause a child process to exit when the parent does

javaprocess

I am launching a child process with ProcessBuilder, and need the child process to exit if the parent process does. Under normal circumstances, my code is stopping the child properly. However, if I cause the OS to kill the parent, the child will continue running.

Is there any way to "tie" the child process to the parent, such that it'll exit when the parent is killed?


Similar questions:

Best Answer

While you cannot protect against a hard abort (e.g. SIGKILL on Unix), you can protect against other signals that cause your parent process to shut down (e.g. SIGINT) and clean up your child process. You can accomplish this through use of shutdown hooks: see Runtime#addShutdownHook, as well as a related SO question here.

Your code might look something like this:

String[] command;
final Process childProcess = new ProcessBuilder(command).start();

Thread closeChildThread = new Thread() {
    public void run() {
        childProcess.destroy();
    }
};

Runtime.getRuntime().addShutdownHook(closeChildThread);