Reputation: 817
I have a binary executable (no source code) which requires this command to be executed in the terminal - export LD_LIBRARY_PATH = "" to link to a library lbtiff.so.3 which I have in a directory. Only after I execute this export command, I can execute the binary, otherwise it gives an error - "error while loading shared libraries: libtiff.so.3...
Now, I want to execute this binary from my java code. But simply executing the export command in the runtime does not do anything and the "error while .." error still occurs when I execute the binary from Java. I guess setting the unix specific environment variable LD_LIBRARY_PATH might not be possible from Java - is there a way I can run my binary from Java and it is able to find the libraries? Here's my current code -
Process p = Runtime.getRuntime().exec("bash -c export LD_LIBRARY_PATH=<lib path>");
p = Runtime.getRuntime().exec("<binary path>");
Upvotes: 2
Views: 21630
Reputation: 122364
Rather than Runtime.exec
, use ProcessBuilder
. That will allow you to specify environment variables when you run the binary that requires them
ProcessBuilder pb = new ProcessBuilder("<binarypath>");
pb.environment().put("LD_LIBRARY_PATH", "<libPath>");
Process p = pb.start();
Your approach with two separate Runtime.exec
calls will not work, because the environment settings you make in the first one only affect that particular Process
, not subsequent processes started by a separate invocation of Runtime.exec
.
Upvotes: 5
Reputation: 11433
See my answer to another question. The best way is to not use an external shell to set the environment variable (your code doesn't work because it will not set the variable globally, only for the bash process), but to set the variable from within Java. Much easier and it works (and on all platforms, regardless of which shell is installed).
Upvotes: 3
Reputation: 25613
On unix systems you can prepend the variable before executing the command
LD_LIBRARY_PATH=... foo args
Will execute the program foo
with args
using the modified LD_LIBRARY_PATH
Or you could take advantage of the subshell by using:
(export LD_LIBRARY_PATH=...; foo args)
Upvotes: 1