java process inputstream,java – 为什么从Process’InputStream块中读取altough数据是可用的...

标签:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值