title: How can I get the PID of a dead child process and use it in the parent?
body: <p>I'm trying to make a C program (for FreeBSD, Unix) which creates 4 children processes in a loop. Each child does things and, when they die, they are replaced immediately by other children. So, in the end, I have 4 children working all the time.</p>
  
  <p>Each child PID has to be registered in a table and, after they're dead, the PID of the table has to be deleted. This is the part in which I'm having troubles.</p>
  
  <p>So in the first try I have tried to create a handler which sends to a global variable the PID of the dead child:</p>
  
  <pre><code>int global_variable;
  
  void handler_SIGCHLD(int sig)
  {
      pid_t son;
      int e;
  
      do {
          son = wait3(&amp;e, WNOHANG, NULL);
          if ((son &gt; (pid_t)0) &amp;&amp; (WIFEXITED(e) || WIFSIGNALED(e)))
          {
              global_variable = son;
          }
      } while (son &gt; (pid_t)0);
  }
  </code></pre>
  
  <p>Then I use it in the parent to delete the PID of the dead child from the table. But then I realise that, if two children die at the same time, one of the PIDs will be overwritten by the other.</p>
  
  <p>How can I avoid this situation? </p>