Java:
Process p = Runtime.getRuntime().exec("myCommand");
final InputStream in = p.getInputStream();
new Thread()
{
public void run()
{
int b;
while ((b = in.read()) != -1) // Blocks here until process terminates, why?
System.out.print((char) b);
}
}.start();
CPP:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char** argv)
{
printf("round 1\n");
// At this point I'd expect the Java process be able
// to read from the input stream.
sleep(1);
printf("round 2\n");
sleep(1);
printf("round 3\n");
sleep(1);
printf("finished!\n");
return 0;
// Only now InputStream.read() stops blocking and starts reading.
}
InputStream.read() 的文档指出:
This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
是的,我知道这一点(因此与 Linux 相关?):
java.lang.Process: Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.
我的问题是:
为什么 InputStream.read() 阻塞,尽管我应该在进程启动后立即获得数据?我是否遗漏了任何一方的东西?
如果是 linux 相关的,有什么方法可以不阻塞地读取进程的输出流吗?
最佳答案
Why does reading from Process' InputStream block although data is available
事实并非如此。这里的问题是当您认为数据可用时,数据并不可用,这是由发送方的缓冲造成的。
您可以根据@MarkkuK. 的评论使用 fflush()
来克服这个问题,或者告诉 stdio
不要缓冲 stdout
所有,按照你的。
关于java - 为什么从 Process 的 InputStream 中读取数据是可用的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18479152/