publicstaticvoid main(String[] args) throws IOException,
InterruptedException {
String command = "java ProcessTest exc";
if (args.length != 0) {
for (int i = 0; i < 200; i++) {
System.out.println(command);
System.err.println(command);
}
} else {
Process process = Runtime.getRuntime().exec(command);
int exitValue = process.waitFor();
System.out.println("exit value = " + exitValue);
}
}
执行java ProcessTest发现程序阻塞。
Process文档描述:由于某些本地平台只提供有限大小的缓冲,所以如果不能迅速地读取子进程的输出流,就有可能会导致子进程的阻塞,甚至是死锁。这恰好就是这里所发生的事情:没有足够的缓冲空间来保存这些输出结果。为了结子进程(Process线程),父进程(Main线程)必须排空它的输出流(标准流与错误流都需要排空),即要去缓存中读取结果:
staticvoid readResult(final InputStream is) {
new Thread(new Runnable() {
publicvoid run() {
try {
// 排空缓存内容
while (is.read() >= 0);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
然后在process.waitFor()之前加上
readResult(process.getErrorStream());
readResult(process.getInputStream());
即可输出exit value = 0。
另外,只能根据process.waitFor返回的结果来判断操作系统命令执行是否成功(成功:0,失败:1),我们不能根据错误流中是否有内容来判断是否执行成功。