java子进程在终止之前不会写入其输出

时间:2013-07-15 17:33:16

标签: java io subprocess

我写了这个简单的测试用例来描述我遇到的问题:

我从Java创建一个子进程,同时启动一个线程,一旦从子进程的标准输出中读取,就应该写每一行。

我得到的是子进程'输出在终止时完全写入。这是输出:

Mon Jul 15 19:17:13 CEST 2013: starting process
Mon Jul 15 19:17:14 CEST 2013: process started
Mon Jul 15 19:17:14 CEST 2013: waiting for process termination
Mon Jul 15 19:17:14 CEST 2013: readerThread is starting
Mon Jul 15 19:17:19 CEST 2013: process terminated correctly
Mon Jul 15 19:17:19 CEST 2013: Thread[Thread-0,5,main] got line: foo(7)
Mon Jul 15 19:17:19 CEST 2013: Thread[Thread-0,5,main] got line: foo(49)
Mon Jul 15 19:17:19 CEST 2013: Thread[Thread-0,5,main] got line: foo(73)
Mon Jul 15 19:17:19 CEST 2013: Thread[Thread-0,5,main] got line: foo(58)
Mon Jul 15 19:17:19 CEST 2013: Thread[Thread-0,5,main] got line: foo(30)
Mon Jul 15 19:17:19 CEST 2013: readerThread is terminating

使用此代码:

public class MiniTest {
    static void println(String x) {
        System.out.println(new Date() + ": " + x);
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder("bin/dummy", "foo", "5");

        println("starting process");
        Process p = pb.start();
        println("process started");

        new ReaderThread(p).start();

        println("waiting for process termination");
        p.waitFor();
        println("process terminated correctly");
    }

    static class ReaderThread extends Thread {
        private Process p;

        public ReaderThread(Process p) {
            this.p = p;
        }

        public void run() {
            println("readerThread is starting");
            BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            try {
                while((line = r.readLine()) != null) {
                    println(this + " got line: " + line);
                }
            } catch(IOException e) {
                println("read error: " + e);
            }
            println("readerThread is terminating");
        }
    }
}

注意:子进程非常简单,它每秒输出一行,用于指定的迭代次数(当在命令行上测试时,它会这样做):

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    char *f = argv[1];
    int n = atoi(argv[2]);
    while(n-- > 0) {
        printf("%s(%d)\n", f, rand() % 100);
        sleep(1);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

通过询问并研究这个问题找到答案。

问题不容易解决,但显然这是一个libc问题。如果输出不是tty / pty,则缓冲不是直接的。

但是有外部程序或脚本允许解决此问题,例如stdbuf或unbuffer(来自expect)。

详细说明:Force line-buffering of stdout when piping to tee