Not able to set LD_LIBRARY_PATH for Java process

后端 未结 2 434
自闭症患者
自闭症患者 2020-12-18 07:33

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:

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 08:24

    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 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.

提交回复
热议问题