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.
Linking it with
libdl.so.2by using-ldlin the makefile solved the problem.