0

I have C++ program (feeder.exe), that prints some data:

printf("%s\n", line);

In average it produces 20-30 lines per second, but not uniformly.

I want to catch this data in Java program by running the exe from Java code:

package temp_read;    
import java.io.*;
public class Main {

    public static void main(String[] args) throws Throwable {
        Process p = Runtime.getRuntime().exec("d:/feeder.exe");
        InputStream is = p.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = in.readLine()) != null) {
            System.out.println(System.currentTimeMillis() + "," + line);
        }
    }
}

But when I look into the output, I see that it receives a bulk of strings once per 3-5 seconds.

Question: how to receive the data from feeder.exe immediately without any delay when it prints to stdout?

PS: not related question: How to stop the feeder.exe if I stop the java by Ctrl+C?

5
  • Try running feeder.exe | more are you are likely to see the same behaviour. I suspect the buffered is in the pipe, not due to how Java reads it. Apr 17, 2013 at 15:16
  • Don't ask unrelated questions in the same Question. Ask as a different Question.
    – Stephen C
    Apr 17, 2013 at 15:20
  • @PeterLawrey, I run it on Windows.
    – Serg
    Apr 17, 2013 at 15:20
  • 1
    @Serg I guess from the d:/feeder.exe You can use the MS-DOS prompt by running CMD Apr 17, 2013 at 15:22
  • 1
    @PeterLawrey, I didn't know Windows has more command. Anyway, I tried, and it produced no effect. But the issue resolved by fflush(stdout);. Thanks.
    – Serg
    Apr 17, 2013 at 15:32

2 Answers 2

2

If redirected, stdout is probably buffered, meaning that the problem is in the C++ code and not on the Java side. The C++ process will buffer the output and flush several "printf"s at once, as soon as the buffer is full.

If you are able to modify the C++ software, try to do a fflush(stdout); after the printf to force the output buffer to be flushed.

0
1

The most likely cause is that the feeder.exe is not flushing its output stream regularly, and the data is sitting in its output buffer until the buffer fills and is written as a result.

If that is the cause, there is nothing you can do on the Java side to avoid this. The problem can only be fixed by modifying the feeder application.


Note that if the data was in the "pipe" that connected the two processes, then reading on the Java side would get it. Assuming that the end-of-line had been written to the pipe, the readLine() call would deliver the line without blocking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.