我写了这个简单的测试用例来描述我遇到的问题:
我从 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;
}