我不确定我是否理解这个问题,但一种方法是调用process.exitValue();
. 如果进程尚未终止,则会引发异常:
/**
* Returns the exit value for the subprocess.
*
* @return the exit value of the subprocess represented by this
* <code>Process</code> object. by convention, the value
* <code>0</code> indicates normal termination.
* @exception IllegalThreadStateException if the subprocess represented
* by this <code>Process</code> object has not yet terminated.
*/
abstract public int exitValue();
如果您不介意 hack,如果您在使用UNIXProcess
该类的 ~Unix 系统上工作,则可以执行以下操作。但是,这确实使用了反射:
ProcessBuilder pb = new ProcessBuilder("/bin/sleep", "5");
Process process = pb.start();
// open accessability of the UNIXProcess.hasExited field using reflection
Field field = process.getClass().getDeclaredField("hasExited");
field.setAccessible(true);
// now we can get the field using reflection
while (!(Boolean) field.get(process)) {
...
}