标签:
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
#include
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
它没有.这里的问题是,当您认为数据不可用时,数据不可用,并且这是由发送方缓冲引起的.
您可以使用fflush()根据@MarkkuK.的评论,或者告诉stdio不要缓冲stdout,就像你的那样.
标签:
来源: https://codeday.me/bug/20190529/1176970.html