当我运行此代码并且调用图非常大时,程序会打印到 opt
输出的最后一行,并在 readLine
处被阻止,即使有精光。有人知道问题是什么吗? opt -print-callgraph file
将调用图发送到错误流。我尝试执行 opt -print-callgraph file 2> callgraph
以便我可以从文件中读取,但它提示位置参数太多。
奇怪的是,代码对于较小的调用图运行良好。
我也尝试使用ProcessBuilder
,但遇到了同样的问题。
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("opt -print-callgraph " + file);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String s = null;
try {
// Gets stuck at readLine after printing out the last line.
while ((s = in.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
in.close();
}
最佳答案
您需要在单独的线程中读取两个流,或者合并它们,以便同时读取它们。否则,如果输出未消耗,则进程可能会阻塞。在这种情况下,stdout
中必须有未使用的输出,这会阻塞进程,这意味着它不会完成,这意味着它不会关闭 stderr,
这意味着读取stderr
将阻塞。
关于java - 从 process.getErrorStream() 读取时 BufferedReader 阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22737932/