5

When I execute a command using ProcessBuilder, how does it know where to look for that command? Using this hack/trick I've modified my PATH variable (verified by inspecting processBuilder.environment()) to be bad (empty, working dir, etc) but ProcessBuilder can still execute sort, echo, bash, etc. just fine. How is it doing this?!

Note: My particular development environment is OSX but this code will also run on Red Hat Enterprise Linux.

Community
  • 1
  • 1
Aaron Silverman
  • 22,070
  • 21
  • 83
  • 103

2 Answers2

5

The documentation says

[...] a command, a list of strings which signifies the external program file to be invoked and its arguments, if any. Which string lists represent a valid operating system command is system-dependent. [...]

Which in essence mean that where it looks for programs to execute depends on the particular system and JVM you're running on.

I can't find a complete matrix of JVM / System behaviors, but supposedly it behaves similar to the popular shells of the system (bash for *nix and cmd for windows) i.e. it searches the directories in the PATH environment variable from left to right and executes the first executable file it finds.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • I see you found my follow up question :-P To clarify I am running on OSX and wondering if there is any way to modify where it looks. – Aaron Silverman Feb 20 '12 at 21:32
  • 1
    Hmm.. beats me. Let's just wait and see if someone comes around and answers this. It seems like the `ProcessBuilder` must have some fallback mechanism which it checks in addition to the PATH variable. – aioobe Feb 20 '12 at 21:43
  • 1
    1.7.0_51 on OSX and I can't get it to look at PATH. Only full path in constructor works – Martin Paljak Jan 25 '14 at 19:17
1

If you want to take control of finding commands, then, well, take control of finding commands. Don't let ProcessBuilder search. Use your own code to find what you want to run, and then put an absolute pathname into the parameter to ProcessBuilder.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
  • 3
    I am trying to write a unit test for something that uses the ProcessBuilder to execute "sort", which wants ProcessBuilder to do the search. I was just trying to simulate sort not being found. – Aaron Silverman Feb 21 '12 at 16:20