Reputation: 1
I use ProcessBuilder
to spawn a child process for executing writing some data to file system. And a problem occurs because the parent process may crash/ killed unexpectedly, the child process just hangs even I use e.g. jps
checking if its parent process dies then exits. What is the right way for a spawned child process to detects if its parent process is dead and then exit?
Also, After searching on the internet, most solution use Runtime.addShutdownHook()
, but this is not provided in ProcessBuilder
. Does it have equivalent one?
Upvotes: 0
Views: 2699
Reputation: 1
In a similar situation I implemented a heartbeat mechanism where the parent process had to regularly send heartbeats. If that did not happen the child process would shut itself down.
Upvotes: 0
Reputation: 3258
You did a good search around the problem. So you may want to use the returned reference to the Process
instance and the Runtime.addShutdownHook(Thread)
method you mentioned. This is the last step that I believe you need to take:
List commands = new ArrayList();
commands.add("xeyes"); // launch this command
ProcessBuilder pb = new ProcessBuilder(commands);
final Process p = pb.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
p.destroy();
}
});
Thread.sleep(2000); // sleep for some time
Upvotes: 3