Sunday, May 1, 2011

Process not found when running from getRuntime.exec() from the JVM

I am trying to run the following code from within Eclipse:

Process process = Runtime.getRuntime().exec("gs");

However I get the exception:

java.io.IOException: Cannot run program "gs": error=2, No such file or directory

Running gs from the command prompt (OS X) works fine from any directory as it is on my PATH. It seems eclipse doesn't know about my path environment variable, even though I have gone into run configurations and selected PATH on the environment tab.

In additional effort to debug this issue I tried the following code:

Process process = Runtime.getRuntime().exec("echo $PATH");
InputStream fromStdout = process.getInputStream();
byte[] byteArray = IOUtils.toByteArray(fromStdout);
System.out.println(new String(byteArray));

The output was $PATH, hmm. Can someone nudge me in the correct direction?

From stackoverflow
  • you are assuming that exec() uses a shell to execute your commands (echo $PATH is a shell command); for the sake of simplicity you can use System.getenv() to see your $PATH:

        System.out.println(System.getenv("PATH"));
    

    EDIT

    Often a better and flexible alternative to Runtime.exec() is the ProcessBuilder class.

0 comments:

Post a Comment