3

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

tried this...this time the error message didn't appear. Nothing was displayed on console. Also HelloWorld.exe was also not created.
Try some experiments. 1) Try to run the command from the windows command prompt. 2) Replace "gcc HelloWorld.c -o HelloWorld.exe" with "cat HelloWorld.c" or "ls -l HelloWorld.c" or "ls -ld ."
0

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);

1 Comment

That won't help. Read the javadoc for exec(String) to understand how it splits the string into arguments.
0

try

/usr/bin/gcc

rather than

gcc

say, use full path for binaries call in script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.