Judah Flynn
Judah Flynn

Reputation: 544

java runtime redirect c program output

I have a problem redirect a c program to java runtime class. It's a similar problem like

Java Runtime execute C language program get no output

However, the answer doesn't help me, and I am guessing because I am in windows environment. I have installed Cygwin and add the path C:\cygwin64\bin to my environment to run my c program. My C program is below and compiled as a.exe:

#include<stdio.h>
int main() {
    printf("Hello World");
    return 0;
}

In my java program:

Process p = Runtime.getRuntime().exec("C:\\a.exe");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while (in.ready()) {
        System.out.println(in.readLine());
    }

This code prints nothing. However, If I changed

Process p = Runtime.getRuntime().exec("C:\\a.exe");

to other bash commands like

Process p = Runtime.getRuntime().exec("ls -la");

It works!

I have tried use ProcessBuilder to redirect the output, running "a.exe" doesn't work but "ls -la" works. This is the code:

File output = new File("C:\\outputfile.txt"); 
ProcessBuilder pb = new ProcessBuilder("C:\\a.exe").inheritIO();
pb.redirectOutput(output);
Process p = pb.start();

My guesses are something related Cgywin but I have no idea how to fix this. Does anyone know what's wrong? Thanks in advance,

Upvotes: 1

Views: 242

Answers (1)

Judah Flynn
Judah Flynn

Reputation: 544

After I have spent all day doing this research, and finally I fix this by restarting my computer..... and everything works....

Upvotes: 1

Related Questions