我试图在Linux上使用LD_PRELOAD
来包装调用system
函数来添加一些预处理的参数。这里是我的system.cpp
:系统()函数不从LD_PRELOAD'ed库调用
#define _GNU_SOURCE
#include <dlfcn.h>
#include <string>
#include <iostream>
typedef int (*orig_system_type)(const char *command);
int system(const char *command)
{
std::string new_cmd = std::string("set -f;") + command;
// next line is for debuggin only
std::cout << new_cmd << std::endl;
orig_system_type orig_system;
orig_system = (orig_system_type)dlsym(RTLD_NEXT,"system");
return orig_system(new_cmd.c_str());
}
我
g++ -shared -fPIC -ldl -o libsystem.so system.cpp
产生的。所以对象建立它。然后,我
$ LD_PRELOAD=/path/to/libsystem.so ./myprogram
运行我的程序我没有得到任何错误 - 但似乎我的system
功能不被调用。使用LD_DEBUG=libs
运行,我可以看到我的.so正在加载,但是我的system
函数未被调用,而是从标准库调用函数。
我需要更改代码/构建才能使其运行?
是的!就是这样。我确实想知道名称改写,因为'strings libsystem.so | grep系统'有一些围绕'system'函数名称的问题。使用'extern“C”'它现在可以正常工作! –