Reputation: 137
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
Upvotes: 3
Views: 539
Reputation: 9216
You can get the current run-time environment and invoke exec method. Here is an example:
String cmd="C:/cygwin/bin/sh -c '/usr/bin/gcc HelloWorld.c -o HelloWorld.exe'";
Process process = Runtime.getRuntime().exec(cmd);
Upvotes: 0
Reputation: 719426
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.
Upvotes: 2
Reputation: 2278
try
/usr/bin/gcc
rather than
gcc
say, use full path for binaries call in script.
Upvotes: 0