title: Can alarm(int) override sleep(int) in C?
body: <p>I've created a <code>signal handler</code> for <code>alarm()</code>. The parent forks out another process which will not have the pending alarm signal. So, the alarm is only invoked in the parent process.
  But as the <code>alarm(2)</code> is invoked, it overrides the <code>sleep(10)</code> in the parent process. Parent only waits for 2 seconds before printing :</p>
  
  <pre><code>"parent retval=8"
  </code></pre>
  
  <p>Whereas the child waits 10 seconds. Why does the <code>alarm()</code> signal override <code>sleep()</code> and does sleep return anything (obviously it does in this case, but why? <code>sleep()</code> shouldn't return anything, right?)?</p>
  
  <p>The code is given below. </p>
  
  <pre><code>&lt;headers&gt;
  
  pid_t cpid;
  
  int main() {
      int retval;
      signal(SIGALRM, handler);
      alarm(2);
      if ((cpid = fork()) == 0) {
          printf(“I’m the child\n”);
          retval = sleep(10);
          printf(“child retval=%d\n”, retval);
      }
      else {
          printf(“I’m the parent\n”);
          retval = sleep(10);
          printf(“parent retval=%d\n”, retval);
      }
  }
  
  /* Handle SIGALRM */
  void handler(int sig)
  {
      if (cpid == 0)
          printf(“running child handler\n”);
      else
          printf(“running parent handler\n”);
  }
  </code></pre>