lecardo lecardo - 7 months ago 71
Java Question

Using Java's process builder to call a C program

Trying to call a C program using Java's process builder but don't know what to call in the process builder call.

Process p = new ProcessBuilder("myCommand", "myArg").start();


For
myCommand
and
myArg
, what values would I replace it with for it to run a C Program? The program I want it to call is shown here:

calculator.c:

#include <stdio.h>

int main ()
{
int a = 4;
int b = 2;
int c = a + b;
printf("Result: %d \n", c);
}

Answer

If calculator.c has not been compiled yet, you will want to first compile it:

Process compile = new ProcessBuilder("gcc", "calculator.c").start();
Process execute = new ProcessBuilder("./a.out").start();

Any relevant compiler flags (e.g., -O or -o calculator) should be included in the arguments as well. If you do rename the executable, you'll want to change ./a.out with it.

A better way (in terms of having few hard-coded constants) would be to have some variables like:

String c_file = "calculator.c";
String output_exe = "calculator";
Process compile = new ProcessBuilder("gcc", "-o " + output_exe,  c_file).start();
Process execute = new ProcessBuilder("./" + output_exe);

Lastly, you'll probably want to make sure each of your processes are exiting without error:

if (compile.getInputStream().read() == -1) {
    // that means something was written to stderr, and you can do something like
    System.out.error("ERROR!");
    System.exit(-1);
}

As @VinayDandekar pointed out, you can also do this with exitValue.

if (compile.exitValue() == -1) {
    // that means something was written to stderr, and you can do something like
    System.out.error("ERROR!");
    System.exit(-1);
}
Comments