Java processbuilder and using environment variables

What I want to do is I want to start a process, however, since the process itself depends on environment variables, calling it directly causes an error in the process. For those who are wondering what it is, a tool rake

. For this reason, I thought it would be better to use bash

and use it through bash

to fix the problem. However, it is not.

Here is my code:

public static void runPB(String directory) throws IOException {
        ProcessBuilder processBuilder = new ProcessBuilder(
                "/bin/bash");
        processBuilder.directory(new File(directory));
        Process process = processBuilder.start();
        OutputStreamWriter osw = new OutputStreamWriter(process.getOutputStream());
        osw.write("rake routes");
        osw.close();
        printStream(process.getErrorStream());
        printStream(process.getInputStream());
    }

    public static void printStream(InputStream is) throws IOException {
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }

      

I know this is an environment related issue because the error I am getting described here cannot load such a file - bundler / setup (LoadError)

Next I checked processBuilder.environment()

returns fewer environment variables than input env

. I went ahead and changed the line osw.write()

and tried echo $GEM_HOME

there that it prints nothing and if I do this on my OS bash then I get the path, I also tried other common things like echo $SHELL

and it prints the location of the shell like in Java code. and in bash.

So my questions are:

1) Why are my operating system environment variables different from the method processBuilder.environment()

?

2) Does the class consider Process

using environment variables issued processBuilder.environment()

? If so, how can we add the missing ones from the operating system level?

+3


source to share


1 answer


1) The variability you see in your java process are those inherited from the process from which you started the java process. That is, if you run it from the shell, it must have the same variables as the shell. You need to figure out which variables are actually set before starting your Java application, and why the expected ones are not set in this context.

To answer part 2, yes, the process will start with the environment in ProcessBuilder.environment()

. You can just add things to the map returned ProcessBuilder.environment()

which will extend the runtime:



ProcessBuilder pb = new ProcessBuilder("foo");
pb.environment().put("MY_VAR", "foobar");

      

+3


source







All Articles