How can I cause a child process to exit when the parent does?

There is no tie between a child process and its parent. They may know each others process ID, but there's no hard connection between them. What you're talking about a orphan process. And it's an OS level concern. Meaning any solution is probably platform dependent.

About the only thing I can think of is to have the child check its parents status periodically, exiting if the parent's shutdown. I don't think this would be all that reliable though.


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

You can simply start a thread reading from System.in in the child process. If you are not writing to stdin of your child, nobody else will do and the thread will block "forever". But you will get an EOF (or an exception), if the parent process is killed or dies otherwise. So you can shutdown the child as well. (Child process started with java.lang.ProcessBuilder)

Tags:

Java

Process