title: wait for children and grand-children
body: <p>How can you wait until all children and grand-children have exited, without blocking in a signal handler? This is my attempt so far.</p>
  
  <pre><code>#include &lt;signal.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;unistd.h&gt;
  
  int run = 1;
  
  void handler(int sig, siginfo_t *info, void *uap)
  {
      int exit_code;
  
      printf("sigchld pid %d\n", info-&gt;si_pid);
      pid_t pid = waitpid(-1, &amp;exit_code, 0);
      if (pid == -1) {
          perror("waitpid()\n");
      } else {
          printf("waitpid returned %d\n", pid);
      }
      // set run = 0 when all children exit
  
      printf("end of sigchild handler\n");
  }
  
  void main() {
  
      struct sigaction chld;
      chld.sa_sigaction = handler;
      chld.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
      sigaction(SIGCHLD, &amp;chld, NULL);
  
      //procmask sigchld?
      if (!fork ()) {
          if (!fork ()) {
              sleep(2);
              printf ("grand-son exit: %d\n", getpid());
              exit (0);
          }
          sleep(1);
          printf ("son exit: %d\n", getpid());
          exit (0);
      }
  
      while(run)
          sleep(1);
  
      printf("ciao\n");
  }
  </code></pre>