Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble getting standard output in Java from a C program with getchar()

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

like image 982
Dan Wanninger Avatar asked Nov 05 '22 19:11

Dan Wanninger


2 Answers

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

like image 85
David Grayson Avatar answered Nov 12 '22 19:11

David Grayson


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.

like image 21
Domingo Ignacio Avatar answered Nov 12 '22 18:11

Domingo Ignacio