为什么从Process的InputStream块读取altough数据是可用的 [英] Why does reading from Process' InputStream block altough data is available

查看:201
本文介绍了为什么从Process的InputStream块读取altough数据是可用的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()的文档声明:

The documentation of InputStream.read() states:


此方法将阻塞,直到输入数据可用,检测到流的末尾或抛出异常。

This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

是的,我知道这个(因此与linux有关吗?):

And yes, I'm aware of this (thus linux related?):


java.lang.Process:由于某些本机平台仅为标准输入和输出流提供有限的缓冲区大小,因此无法及时写入输入流或读取子流程的输出流可能导致子进程阻塞,甚至死锁。

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.

我的问题是:


  1. 为什么InputStream.read()阻塞虽然我应该在进程启动后就已经有了数据?我错过了两边的东西吗?

  1. Why is InputStream.read() blocking although I should already have data available right after the process starts? Am I missing something on either side?

如果它与linux相关,有没有办法从流程的输出流中读取而不阻塞?

If it's linux related, is there any way to read from the process' output stream without blocking?


推荐答案


为什么从Process'InputStream块读取数据虽然数据可用

Why does reading from Process' InputStream block although data is available

它没有。这里的问题是,当您认为数据不是时,数据可用,并且这是由发件人的缓冲引起的。

It doesn't. The problem here is that data isn't available when you think it is, and that's caused by buffering at the sender.

您可以克服用 fflush()根据@MarkkuK。的评论,或告诉 stdio 不要缓冲 stdout ,根据你自己。

You can overcome that with fflush() as per @MarkkuK.'s comment, or by telling stdio not to buffer stdout at all, as per yours.

这篇关于为什么从Process的InputStream块读取altough数据是可用的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆