LD_PRELOAD not working with my program

2019-07-20 11:36发布

问题:

For testing LD_PRELOAD, I wrote my own getpid, which prints something before calling the original getpid using dlsym. The code is given below.

#define _GNU_SOURCE

#include <unistd.h>
#include <stdio.h>
#include <dlfcn.h>

typedef pid_t (*getpidType)(void);

pid_t getpid(void)
{
    printf("Hello, getpid!\n");
    getpidType f = (getpidType)dlsym(RTLD_NEXT, "getpid");
    return f();
}

However when I use such getpid in my program and run it using LD_PRELOAD, by typing LD_PRELOAD=./prelib.so ./prog, I get the following error.

./prog: symbol lookup error: ./prelib.so: undefined symbol: dlsym

But If I do LD_PRELOAD=./prelib.so bash -c 'echo $$', there is no such error. Any idea what is going on here.

回答1:

Linking it with libdl.so.2 by using -ldl in the makefile solved the problem.