I am running a Java process on unix.
I need to run an external process which is spawned by the main process using ProcessBuilder. The main process waits until the external process is done, and then spawnes the next external process. I have got it working till here.
public static void main(String[] args) {
for(...) {
int exitVal = runExternalProcess(args);
if(exitVal !=0) {
failedProcess.add(args);
}
}
}
private int runExternalProcess(String[] args) {
ProcessBuilder pb = new ProcessBuilder(args[0], args[1], args[2]);
pb.redirectErrorStream(true);
Process proc = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
String line = null;
while ( (line = br.readLine()) != null)
LOG.log(Level.SEVERE, line);
//Main thread waits for external process to complete.
//What I need to do is.
// If proc.executionTime() > TIMEOUT
// kill proc;
int exitVal = proc.waitFor();
proc.getInputStream().close();
proc.getOutputStream().close();
proc.getErrorStream().close();
return exitVal;
}
What I am not able to figure out is, how to do this. For some inputs the external process hangs and in such cases, I want to wait for a set timeout period and if the external process is not complete by then, just kill it and return control to the main process (along with exit value so that I can track the failed processes), so that the next external process can be launched.
I tried using proc.wait(TIMEOUT) and then using proc.exitValue(); to get the exit value, but could not get it working.
Thanks!