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?

4

2 回答 2

2

如果重定向,stdout 可能会被缓冲,这意味着问题出在 C++ 代码中,而不是在 Java 端。一旦缓冲区已满,C++ 进程将缓冲输出并一次刷新几个“printf”。

如果您能够修改 C++ 软件,请尝试fflush(stdout);在 printf 之后执行 a 以强制刷新输出缓冲区。

于 2013-04-17T15:16:26.210 回答
1

最可能的原因是feeder.exe没有定期刷新其输出流,并且数据位于其输出缓冲区中,直到缓冲区填满并因此被写入。

如果这是原因,那么您在 Java 端无法采取任何措施来避免这种情况。该问题只能通过修改feeder应用程序来解决。


请注意,如果数据位于连接两个进程的“管道”中,那么在 Java 端读取数据即可。假设已将行尾写入管道,则该readLine()调用将传递该行而不会阻塞。

于 2013-04-17T15:22:41.553 回答