title: fork() not working as expected
body: <p>I am trying to create a program which spawns two processes -- the first of which monitors the second, and restarts it if it is killed. (The idea is that the only way to kill the second process is to first kill the first.) Below I have code that fails to accomplish my goal.</p>
  
  <pre><code>#include &lt;cstdio&gt;
  #include &lt;unistd.h&gt;
  #include &lt;thread&gt;
  #include &lt;chrono&gt;
  #include &lt;signal.h&gt;
  #include &lt;cerrno&gt;
  
  void makeSiblings();
  
  void run_ping() {
  
    while (true) {
  
      std::this_thread::sleep_for(std::chrono::seconds(2));
      puts("Ping.");
    }
  }
  
  void run_monitor(pid_t sibling) {
  
    while (kill(sibling, 0) != -1 and errno != ESRCH) {
  
      printf("%d still exists.\n", sibling);
      std::this_thread::sleep_for(std::chrono::seconds(1));
    }
  
    makeSiblings();
  }
  
  void makeSiblings() {
  
    pid_t pid1, pid2;
  
    if ((pid1 = fork()) == -1) {
  
      perror("fork");
      exit(EXIT_FAILURE);
    }
  
    if (pid1 == 0) {
  
      setsid();
      run_ping();
    }
  
    if ((pid2 = fork()) == -1) {
  
      perror("fork");
      exit(EXIT_FAILURE);
    }
  
    if (pid2 == 0) {
  
      setsid();
      run_monitor(pid1);
    }
  }
  
  int main() {
  
    makeSiblings();
  }
  </code></pre>
  
  <p>When this code is run, it outputs <code>Ping.</code> and e.g. <code>7812 still exists.</code> every two and one seconds, respectively -- as expected. However, when I from another terminal <code>kill 7812</code>, the "Ping" process proliferates to a ridiculous extent -- I appear to be fork-bombing myself, and it's only through spamming <code>killall</code> that I'm able to recover.</p>
  
  <p>I appear to have failed to understand some subtlety regarding <code>fork()</code>, or perhaps regarding <code>setsid()</code>. I would appreciate a pointer or two.</p>