SDJSK
SDJSK

Reputation: 1326

Java Runtime execute C language program get no output

I write a simple C program, and build it to "AskStack.exe".

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello world!\n");
    getchar();
    return 0;
}

and then i use the java program to exec the C program, i want to get the output.

import java.io.BufferedReader;
import java.io.InputStreamReader;


public class Test {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        Process p = Runtime.getRuntime().exec("AskStack.exe");
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        do{
            line = reader.readLine();
            System.out.println(line);
        }while(line != null);
        p.waitFor();
    }

}

but i failed. the java program did not output anything. i note that if i remove the getchar() of the C program, it will get the output. But my purpose is to interact with the C program.

So how should i modify my java code? thanks in advance.

Upvotes: 2

Views: 509

Answers (1)

Stephen C
Stephen C

Reputation: 719436

Here's what is happening.

  1. The Java program launches the AskMe.exe program.

  2. The AskMe.exe writes a line to the output buffer for stdout

  3. The AskMe.exe calls getChar which blocks waiting for a character on its standard input.

Meanwhile

  1. The Java program attempts to read a line from the child processes standard output.

Deadlock!

The problem is that AskMe.exe has not flushed the standard output buffer yet. And it won't do that until it exits ... after it has read the character that is never going to arrive!

There are a number of possible fixes, including the following:

  • You could remove the getChar() call.

  • You could explicitly flush the stdout stream after the printf. (But that just moves the bug to another place. The Java program will now read and then print "hello world" message, and then wait for the the child process to exit ... which won't ever happen.)

  • You could modify the Java program to write a character to child processes standard input. If you don't modify AskeMe.exe, this has to be done BEFORE the Java program attempts to read from the child ... or you will deadlock, again.

Upvotes: 2

Related Questions