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:
Why is InputStream.read() blocking although I should already have data available right after the process starts? Am I missing something on either side?
If it's linux related, is there any way to read from the process' output stream without blocking?
For example, an InputStream from a Socket socket will block, rather than returning EOF, until a TCP packet with the FIN flag set is received. When EOF is received from such a stream, you can be assured that all data sent on that socket has been reliably received, and you won't be able to read any more data.
The InputStream class of the java.io package is an abstract superclass that represents an input stream of bytes. Since InputStream is an abstract class, it is not useful by itself. However, its subclasses can be used to read data.
Class InputStream. This abstract class is the superclass of all classes representing an input stream of bytes. Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With