title: Learning to fork() idle processes in C++
body: <p>Here's a revision of my programming problem: </p>
  
  <ol>
  <li>Fork off two idle processes that run for a random time, each one
  running between 0 - 20 seconds.</li>
  <li>Processes should use signals SIGSTOP and SIGCONT to schedule the
  processes in a round-robin queue.</li>
  <li>When the child processes BOTH terminate for each idle process, the
  parent should terminate as well.</li>
  <li>If one of the child processes terminate, it should keep going, until
  both of them are terminated using SIGCHLD.</li>
  </ol>
  
  <p>This is about how far I'm at. </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/wait.h&gt;
  
  using namespace std;
  using std::cout;
  
  volatile sig_atomic_t keep_going = 1;
  
  void catch_child (int sig)
  { int status, p;
    p = waitpid(-1,&amp;status,WNOHANG);
    if (p==0) return;
    keep_going=0;
    cout&lt;&lt;"Child process caught: "&lt;&lt; p &lt;&lt;endl;
    return;
  }
  
  
  int  main()
  {
    pid_t pid;
    pid_t mypid;
    int rand1;
  
    rand1 = rand()%20;    
  
    signal (SIGCHLD, catch_child);
  
    pid = fork();
    if (pid&lt;0) {
      cout&lt;&lt;"Error\n";
      return 0;
    }
    else if (pid==0) {
  
  
      mypid = getpid();
      cout &lt;&lt; "Child pid is " &lt;&lt; mypid &lt;&lt; "\n";
      execlp("./idle","./idle","1",rand1,0);
    } else {
      mypid=getpid();
  
      cout&lt;&lt;"parent procss is "&lt;&lt;mypid&lt;&lt;" and child is "&lt;&lt;pid&lt;&lt;"\n";
      sleep(5);
  
      cout&lt;&lt;"pausing child "&lt;&lt;pid&lt;&lt;" for 5 seconds\n";
      kill(pid,SIGSTOP);
  
      for (int i=0; i&lt;5; i++) sleep(1);
  
      cout&lt;&lt;"Resuming child "&lt;&lt;pid&lt;&lt;"\n";
      kill(pid,SIGCONT);
  
      cout&lt;&lt;"Parent process pid is "&lt;&lt;mypid&lt;&lt;" waiting for child to stop\n";
      while (keep_going==1) sleep(1);
      // wait(NULL);
  
  
      cout &lt;&lt;"Parent knows that Child now done\n";
    }
    return 0;
  }
  </code></pre>