title: Run-time library interposition for sleep() function in C
body: <p>I'm having a slight problem with interpositioning the sleep function at run time. I'm currently trying to test library interpositioning at runtime using a simple source code, "sleepdemo.c" and "wakeup.c".</p>
  
  <p>The code(wakeup.c) I have wrote is as following: </p>
  
  <pre><code>  1 #ifdef RUNTIME
    2 #define _GNU_SOURCE
    3 #include &lt;stdio.h&gt;
    4 #include &lt;unistd.h&gt;
    5 #include &lt;dlfcn.h&gt;
    6 #include &lt;stdlib.h&gt;
    7
    8 /* sleep wrapper function*/
    9 unsigned int wakeup(unsigned int secs)
   10 {
   11         unsigned int (*wakeupp)(unsigned int secs);
   12         char *error;
   13
   14         wakeupp = dlsym(RTLD_NEXT, "sleep"); //Get address of sleep
   15         if((error = dlerror()) != NULL){
   16                 fputs(error, stderr);
   17                 exit(1);
   18         }
   19
   20         unsigned int elapsed = sleep(secs);
   21         printf("Woke up at %d secs.\n", secs - elapsed+1);
   22         return elapsed;
   23 }
   24
   25 #endif
  </code></pre>
  
  <p>And this is the code I'm trying to interpose:</p>
  
  <pre><code>  1 #include &lt;stdio.h&gt;
    2 #include &lt;stdlib.h&gt;
    3 #include &lt;unistd.h&gt;
    4
    5 int main()
    6 {
    7         int secs = 1;
    8
    9         printf("This is sleep demo program.\n");
   10         sleep(secs);
   11         return 0;
   12 }
  </code></pre>
  
  <p>And I have given following instructions to my gcc to create an shared library:</p>
  
  <pre><code>gcc -DRUNTIME -shared -fpic -o mysleep.so wakeup.c -ldl
  LD_PRELOAD="./mysleep.so" ./wakeup
  </code></pre>