LD_LIBRARY_PATH在程序运行时用setenv修改,如何生效
大家好:小弟现在有这样一个需求,我们的程序运行时会依赖一些so动态库文件,为了尽量实现绿色化,不想把依赖的so放入/usr/lib或用户的$HOME/lib下,想通过运行时修改LD_LIBRARY_PATH来实现,写了个测试代码,setenv之后,调用getenv确是把值修改了. 但是加载so 仍然失败.
在shell里,可以使用export LD_LIBRARY之类的东东,使得当前进程和子进程等生效了.
不知代码如何实现这样的功能.
以下我的测试代码.
#include <stdlib.h>
#include <dlfcn.h>
#include <stdio.h>
#include <string.h>
int loadso(const char* file)
{
void* h = dlopen(file, RTLD_LAZY);
if (NULL != h)
{
fprintf(stdout, "load file %s Ok, handle=%p\n", file, h);
dlclose(h);
}
else
{
fprintf(stdout, "load file %s failed, err=%s\n", file, dlerror() );
}
return 0;
}
int main(int argc, char* argv[])
{
const char* so_name = "libfoo.so";
const char* so_dir = "/home/extend/test/libs";
char ld_path = {0};
const char* psz_ld_path = getenv("LD_LIBRARY_PATH");
const char* psz_path = getenv("PATH");
if (psz_ld_path != NULL)
strcpy(ld_path, psz_ld_path);
sprintf(ld_path + strlen(ld_path), ":%s", so_dir);
fprintf(stdout, "org: ld_path = %s\n", psz_ld_path);
loadso(so_name);
setenv("LD_LIBRARY_PATH", ld_path, 1);
psz_ld_path = getenv("LD_LIBRARY_PATH");
fprintf(stdout, "new: ld_path = %s\n", psz_ld_path);
loadso(so_name);
return 0;
}
你解决了吗?我有同样的问题。 回复 1# bbxyard
http://stackoverflow.com/questions/6713692/problems-with-using-setenv-and-then-making-the-dlopen-call
动态更换LD_LIBRARY_PATH貌似是不行了,但是可以用chdir动态改变当前工作路径来解决。(LD_LIBRARY_PATH可以带上当前路径".",需要被依赖的地方就cd过去)。
页:
[1]