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;
}
我无法弄清楚的是,如何做到这一点.对于某些输入,外部进程挂起,在这种情况下,我想等待一个设置的超时时间,如果那时外部进程没有完成,只需将其终止并将控制权返回给主进程(以及退出值以便我可以跟踪失败的进程),以便可以启动下一个外部进程.
我尝试使用proc.wait(TIMEOUT)然后使用proc.exitValue();获取退出值,但无法使其正常工作.
谢谢!