title: C++ fork() -- creating a "list" of processes
body: <p>I have a program that creates new processes "one by one". Is it possible to change this code so it creates a "list" of processes &ndash; i.e. child 1 being the parent of child 2, child 2 being the parent of child 3, etc.?</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;iostream&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;unistd.h&gt;
  #include "err.h"
  
  using namespace std;
  int main ()
  {
   pid_t pid;
   int i;
  
   cout &lt;&lt; "My process id = " &lt;&lt; getpid() &lt;&lt; endl;
  
   for (i = 1; i &lt;= 4; i++)
    switch ( pid = fork() ) {
    case -1:
      syserr("Error in fork");
  
    case 0:
      cout &lt;&lt; "Child process: My process id = " &lt;&lt; getpid() &lt;&lt; endl;
      cout &lt;&lt; "Child process: Value returned by fork() = " &lt;&lt; pid &lt;&lt; endl;
      return 0;
  
    default:
      cout &lt;&lt; "Parent process. My process id = " &lt;&lt; getpid() &lt;&lt; endl;
      cout &lt;&lt; "Parent process. Value returned by fork() = " &lt;&lt; pid &lt;&lt; endl;
  
     if (wait(NULL) == -1) 
     syserr("Error in wait");
  
   }  
   return 0;
   }
  </code></pre>