Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

linux - Not able to set LD_LIBRARY_PATH for Java process

I am trying to call my linux executable from shell script. Before calling this executable, I want to set LD_LIBRARY_PATH with specific values. My shell script is as below:

Parent.sh (contains 2 lines)

   - source set_env.sh 
   - executable.so

Set_env.sh

   - setenv LD_LIBRARY_PATH /proj/something

On manually executing Parent.sh scipt from linux console, the executable.so is called with LD_LIBRARY_PATH set correctly. But after integrating it wiht java code as:

String[] commandArray ={"Parent.sh"};
Runtime runtime = Runtime.getRuntime();
Process javap = runtime.exec(commandArray);
javap.waitFor();

LD_LIBRARY_PATH is not set for executable.so

I hope description is clear :)

Please let know whats wrong in the code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Dunes answer solves your problem, but I would strongly suggest a different approach in this particular case. Instead of relying on a shell to set the environment arguments, you should do this in your Java code. This way you don't need to know which shells exist on the system and what their language is, it will just work on all platforms.

To do this, you can use the Runtime.exec(String[] cmd, String[] environment) overload (javadoc). As the second parameter you can pass an array which contains all the environment variables the subprocess will see.

A little bit nicer even is the ProcessBuilder API:

ProcessBuilder pb = new ProcessBuilder("executable.so");
Map<String, String> env = pb.environment();
env.put("LD_LIBRARY_PATH", "/proj/something");
Process javap = pb.start();
javap.waitFor();

This way, the subprocess will inherit all environment variables from the Java process, and additionally have the LD_LIBRARY_PATH variable set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...