I am trying to compile a C program through a javacode. I did it as follows.
Process process = Runtime.getRuntime().exec("C:/cygwin/bin/sh -c 'gcc HelloWorld.c -o HelloWorld.exe'");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line, log;
log ="\n..Input..\n";
while ((line = br.readLine()) != null) {
log+=line;
log+="\n";
}
InputStream is2 = process.getErrorStream();
InputStreamReader isr2 = new InputStreamReader(is2);
BufferedReader br2 = new BufferedReader(isr2);
String line2;
log+="\n..Error..\n";
while ((line2 = br2.readLine()) != null) {
log+=line2;
log+="\n";
}
System.out.println(log);
HelloWorld.exe is not created and following error message was displayed. /usr/bin/sh: gcc: command not found
One problem is that exec(String) splits the string into arguments naively at the white-space characters. You need to do the splitting for it. write the exec as:
Process process = Runtime.getRuntime().exec(new String[]{
"C:/cygwin/bin/sh",
"-c",
"gcc HelloWorld.c -o HelloWorld.exe"});
The exec(String) method does not understand shell syntax such as quoting and redirection.
It might also be necessary to use a full pathname for the gcc command, but I doubt it. The shell should inherit the environment variable settings from the JVM, and that probably includes a suitable PATH variable.
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