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:
If the parent is killed, children become children of the init process (that has the process id 1 and is launched as the first user process by the kernel). The init process checks periodically for new children, and waits for them (thus freeing resources that are allocated by their return value).
The parent can use the system call wait() or waitpid() along with the macros WIFEXITED and WEXITSTATUS with it to learn about the status of its stopped child. (*)wait() system call : It suspends execution of the calling process until one of its children terminates. Syntax of wait() system call: pid_t wait(int *status);
The idea is to create a "job object" for your main application, and register your child processes with the job object. If the main process dies, the OS will take care of terminating the child processes.
1 Answer. Show activity on this post. If you are on the same terminal with the process, type ctrl-z to stop the parent, and the use ps -ef to find the PID of the php child. Use the kill lines above to effectively separate the child from the parent.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With