Java, wait for the child process to exit
Using Java's processbuilder, I'm creating a set of subprocesses I can use the waitfor () method in the generated process object to wait for the specific subprocess to exit
Can any child process be blocked in the way of UNIX wait() system call?
Solution
The first step is to express the work completed by each sub process as future, as shown below:
final ProcessBuilder builder = ...; // for each process you're going to launch FutureTask task = new FutureTask(new Callable<Integer>() { @Override public Integer call() { return builder.start().waitFor(); } };
Now submit all tasks to the performer:
ExecutorService executor = Executors.newCachedThreadPool(); for (FutureTask task : tasks) { executor.submit(task); } // no more tasks are going to be submitted,this will let the executor clean up its threads executor.shutdown();
Now use the excellent executorcompletionservice class:
ExecutorCompletionService service = new ExecutorCompletionService(executor); while (!executor.isTerminated()) { Future<Integer> finishedFuture = service.take(); System.out.println("Finishing process returned " + finishedFuture.get()); }
This loop will iterate once at the completion of each task ReturnValue will be the exit code of the child process
Now, you don't know exactly which process has been completed You can change the callable instead of returning an integer to return process, or better yet, your own class to represent the output of the process
Oh, of course, if you don't care about waiting for all the tasks, you can call take () only once