我已经为 open()
系统调用编写了一个包装器,并使用 LD_PRELOAD
环境变量预加载它。我只希望程序的几个函数使用修改后的 open()
而其他函数将使用原始函数。将两个程序中的功能分开不是一种选择,因为一个调用另一个。怎么做到的?
最佳答案
下面例子中函数插入的使用类似于this answer .
该示例提供了一个调用原始write()
的write()
包装函数。重要的是要注意,您不能直接调用原始的 write()
,因为它将被解释为对包装器的调用。 main()
中函数指针的使用演示了如何避免混淆调用的 write()
。
代码:test.c
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <dlfcn.h>
size_t write(int fd, const void *buf, size_t count)
{
static size_t (*write_func)(int, const void *, size_t) = NULL;
/* get reference to original (libc provided) write */
if (!write_func)
{
write_func = (size_t(*)(int, const void *, size_t)) dlsym(RTLD_NEXT, "write");
}
/* perform wrapper specific actions */
/* ... */
/* call original write() */
return write_func(fd, buf, count);
}
int main(int argc, char *argv[])
{
size_t (*wrap_write)(int, const void *, size_t);
size_t (*orig_write)(int, const void *, size_t);
char buf1[] = "write() wrapper called\n";
char buf2[] = "orignial write() called\n";
/* set pointer to write() wrapper to differentiate */
wrap_write = write;
/* get reference to original (libc provided) write() */
orig_write = (size_t(*)(int, const void *, size_t)) dlsym(RTLD_NEXT, "write");
/* call write() wrapper */
wrap_write(1, buf1, strlen(buf1));
/* call original write() */
orig_write(1, buf2, strlen(buf2));
return 0;
}
输出:
$ gcc -Wall -Werror -ldl test.c -o test
$ ./test
write() wrapper called
orignial write() called
$
关于c - 为一些功能预加载我的库,同时使用其他人使用 LD_PRELOAD 的原始库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5203846/