title: Replacing getpid with my own implementation
body: <p>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:</p>
  
  <pre><code>pid_t getpid(void)
  {
      if (gi_PID != -1)
      {
          return gi_PID;
      }
      else
      {
          // OS level getpid() function
      }
  }
  </code></pre>
  
  <p>How can I call the original getpid() implementation of the OS through this function?</p>
  
  <p>EDIT: I tried:</p>
  
  <pre><code>pid_t getpid(void)
  {
      if (gi_PID != -1)
      {
          return gi_PID;
      }
      else
      {
          return _getpid();
      }
  }
  </code></pre>
  
  <p>as Jonathan has suggested. This gave me the following errors when compiling with g++:</p>
  
  <blockquote>
    <p>In function <code>pid_t getpid()':
    SerendibPlugin.cpp:882: error:
    </code>_getpid' undeclared (first use this
    function) SerendibPlugin.cpp:882:
    error: (Each undeclared identifier is
    reported only once for each function
    it appears in.)</p>
  </blockquote>
  
  <p>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").</p>
  
  <p>Here's my sample code:</p>
  
  <pre><code>vi xx.c
  "xx.c" 23 lines, 425 characters 
  #include &lt;sys/types.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;iostream&gt;
  #include &lt;dlfcn.h&gt;
  
  using namespace std;
  pid_t(*___getpid)();
  
  pid_t getpid(void)
  {
      cout &lt;&lt; "My getpid" &lt;&lt; endl;
      cout &lt;&lt; "PID :" &lt;&lt; (*___getpid)() &lt;&lt; endl;
      return (*___getpid)();
  }
  
  int main(void)
  {
      ___getpid = (pid_t(*)())dlsym(RTLD_NEXT, "getpid");
      pid_t p1 = getpid();
      printf("%d \n", (int)p1);
      return(0);
  }
  </code></pre>
  
  <p>g++ xx.c -o xout</p>
  
  <pre><code>My getpid
  PID :7802
  7802 
  </code></pre>