Why does reading from Process' InputStream block altough data is available
Asked Answered
B

2

11

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.
}

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.

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

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.

My questions are:

  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?

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

Birmingham answered 28/8, 2013 at 3:54 Comment(3)
Try adding a fflush(stdout) after each printf().Kele
Actually that worked! Thank you. Also, I've found a more general solution: setbuf(stdout, NULL), #1716796Birmingham
Upvoted pointless unexplained downvoteBukhara
B
11

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.

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

Bukhara answered 28/8, 2013 at 6:10 Comment(3)
Thank you, that sums it up!Birmingham
How to make sure it is not blocked when external process is not ours?Illicit
@Illicit You can't.Bukhara
H
0

There is an other solution I posted here, which consists in using InputStream#available() before reading anything from Process streams.

Handal answered 25/1, 2015 at 4:19 Comment(1)
And then what? Sleep? Makes no difference in the end.Bukhara

© 2022 - 2024 — McMap. All rights reserved.