I'm writing a terminal wrapper for a command-line program in Java, and I spawn the subprocess using ProcessBuilder. To send keystrokes to the subprocess, I just write e.getKeyChar()
from the GUI straight to the OutputStream
given by proc.getOutputStream()
. To receive output from the subprocess, I basically have a while loop that reads from the subprocess's stdout
:
while ((b = br.read()) != -1) {
System.out.println("Read "+b);
bb[0] = (byte) b;
// call an event listener with the read byte
listener.dataReceived(bb);
}
This works, only if I immediately flush the output on both ends. That is, I have to flush every user input and the subprocess has to flush its own stdout
in order for stuff to happen. Otherwise, read()
blocks, waiting for data, which is never actually sent (subprocess' stdout just keeps buffering). How can I get I/O going?
Example terminal subprocess:
#include <stdio.h>
int main() {
char c;
while((c = getchar()) != -1) {
printf("Got: %d\n", c);
// doesn't work in my Java program if the next line isn't present
fflush(stdout);
}
return 0;
}
I'm running on Ubuntu 10.10 with Sun Java 6.