I have an application where I need to write a new getpid function to replace the original one of the OS. The implementation would be similar to:
pid_t getpid(void) { if (gi_PID != -1) { return gi_PID; } else { // OS level getpid() function } }
How can I call the original getpid() implementation of the OS through this function?
EDIT: I tried:
pid_t getpid(void) { if (gi_PID != -1) { return gi_PID; } else { return _getpid(); } }
as Jonathan has suggested. This gave me the following errors when compiling with g++:
In function
pid_t getpid()': SerendibPlugin.cpp:882: error:_getpid’ undeclared (first use this function) SerendibPlugin.cpp:882: error: (Each undeclared identifier is reported only once for each function it appears in.)
EDIT 2: I’ve managed to get this to work by using a function pointer and setting it to the next second symbol with the id ‘getpid’, using dlsym(RTLD_NEXT, ‘getpid’).
Here’s my sample code:
vi xx.c 'xx.c' 23 lines, 425 characters #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <iostream> #include <dlfcn.h> using namespace std; pid_t(*___getpid)(); pid_t getpid(void) { cout << 'My getpid' << endl; cout << 'PID :' << (*___getpid)() << endl; return (*___getpid)(); } int main(void) { ___getpid = (pid_t(*)())dlsym(RTLD_NEXT, 'getpid'); pid_t p1 = getpid(); printf('%d \n', (int)p1); return(0); }
g++ xx.c -o xout
My getpid PID :7802 7802
On many systems, you will find that
getpid()is a ‘weak symbol’ for_getpid(), which can be called in lieu ofgetpid().The first version of the answer mentioned
__getpid(); the mention was removed swiftly since it was erroneous.This code works for me on Solaris 10 (SPARC) – with a C++ compiler:
This code works for me on Solaris 10 (SPARC) – with a C compiler: