为什么从Process'InputStream块中读取altough数据是可用的

bca*_*use 5 java linux

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();
Run Code Online (Sandbox Code Playgroud)

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.
}
Run Code Online (Sandbox Code Playgroud)

InputStream.read()的文档说明:

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

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

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

我的问题是:

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

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

use*_*421 7

尽管数据可用,为什么要从Process'InputStream块读取

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

您可以fflush()根据@ MarkkuK.的评论,或者根据您的说法,stdio根本不告诉您缓冲stdout.