io - java subprocess does not write its output until it terminates -


i've written simple testcase describes problem i'm having:

i create subprocess java, , simultaneously start thread should write every line read subprocess' standard output.

what instead subprocess' output entirely written when terminates. here output:

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 process termination mon jul 15 19:17:14 cest 2013: readerthread 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 terminating 

with code:

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 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 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 terminating");         }     } } 

note: subprocess simple, outputs line every second, specified abount of iterations (and when tested on command line, so):

#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; } 

found answer asking around , studying on issue.

the problem cannot solved, apparently it's libc issue. if output it's not tty/pty, buffering not line.

there external programs or script allow work around this, example stdbuf or unbuffer (from expect).

detailed explanation: force line-buffering of stdout when piping tee


Comments