c - 为一些功能预加载我的库,同时使用其他人使用 LD_PRELOAD 的原始库

标签 c linux wrapper

我已经为 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/

相关文章:

c - 使用 "console font-size"中的 "GetCurrentConsoleFont()"检索 "Windows XP"失败?

c++ - Linux 上的共享库和链接 (elf)

c - 在运行时确定操作系统

mysql - 如何将大文件加载到 MySQL 中的表中

python - 使用 ctypes 将 (uint8) NumPy 数组从 python 传递到 c++

ios - bool 包装器?创建一个值为 `BOOL` 的对象。 ( objective-C )

java - 用通用功能包装代码,同时传递参数

C 在赋值中相当于 Python 的 "or"

c - 32 位编译在 64 位 Ubuntu 16.04 上失败

linux - 从 bash 并行运行多个脚本而不将输出打印到控制台