I'm trying to call a C program from Java and capture the standard output. Here is my code:
try {
ProcessBuilder pb = new ProcessBuilder("helloworld.exe");
pb.redirectErrorStream(true); // Merge std out and std err into same stream
program = pb.start(); // Start program
BufferedReader input = new BufferedReader(new InputStreamReader(program.getInputStream()));
line = input.readLine();
while (line != null) {
System.out.println(line);
line = input.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
Here is a sample c program:
int main(){
printf("Hello world\n");
}
This works fine when the program I'm executing (helloworld in this case) does not have a getchar()
in it. However, if I add a getchar()
right after the printf, I never get anything off the input stream. Any ideas why?
Thanks
As Kyle you said, you may need to flush the output stream after calling print to make sure the characters actually go to the standard output without delay. You should do this in both programs. This can be done in C with fflush(stdout);
and can probably be done in Java with something like System.out.flush()
.
--David
Because when the C program calls getchar, the C program stops to wait for input. And the input never comes! After all, your Java program captures stdout/stderr, but does nothing about attaching to stdin.
Use the getOutputStream() instance method in the Process class on your program
object to get the stream representing stdin, analogous to getInputStream().
Then send the data to the C program that the C program expects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With