title: Exec To Another Program + Child Death
body: <p>I'm trying to write a program where, based on a user input value 'n', I'm going to fork that many processes to run <em>simultaneously</em>. In addition, each child is trying to exec to another file that I've created, that will generate a x sleep time, and a x exit value. Ultimately, when a child dies, the parent needs to print the pid and exit_status. The important part is making sure that children death is x, and not concurrent. So far, there's two things I can't figure out.</p>
  
  <ol>
  <li>Getting my execl to run my sleep.c file (as provided below). </li>
  <li>Getting the children to fork and die randomly, not in an orderly fashion, and as a result printing who died, with their generated random exit status. </li>
  </ol>
  
  <p>I have two files, Sleep.c and Ranchild.c.</p>
  
  <p>SLEEP.C
  <code></p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;time.h&gt;
  
  /* Generated random sleep time, and return random exit value */
  
  int main()
  {
      /* Calculate A Random Time To Sleep 1 - 10 Seconds*/
      srand(time(NULL));
      int r = (rand() % 10) + 1;
  
      printf("Sleep Time: %d\n", r);
      sleep(r);
  
      /* Calculate A Random Exit Value */
      int r2 = (rand() % 30) + 1;
      exit(r2);       
  }
  </code></pre>
  
  <p></code> </p>
  
  <p>RANCHILD.C
  <code></p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;time.h&gt;
  
  int main()
  {
      /* Get User Input */
      int i, n;
  
      printf("Please Enter An Integer!\n");
  
      /* Test User Input */
      if(!scanf("%d", &amp;n)) {
          printf("Invalid Input!\n");
          return -1;
      }   
  
      /* Initialize Needed Variables */
      pid_t pid[n];
      int status, exit_status;
  
      for(i = 0; i &lt; n; i++) {
  
          if((pid[i] = fork()) &lt; 0) {
              perror("Fork Failed!");
              return -2;
          }
  
          if(pid[i] == 0) {
              execl("sleep", "sleep", (char *)0);
  } else {
      /* Print Child Results */
      if (waitpid(-1, &amp;status, WNOHANG) == 0) {
          if(WIFEXITED(status)) {
              exit_status = WEXITSTATUS(status);
              printf("Exit Status From %d was %d!\n", pid[i], exit_status);
          }
      }   
  
  }       
      }
  
      exit(0);
  }
  </code></pre>
  
  <p></code></p>
  
  <p>It never manages to exec to the Sleep file, and a sample of the result is this:
  <code></p>
  
  <pre><code>3
  Exit Status From 27369 was 0!
  Exit Status From 27370 was 0!
  Exit Status From 27371 was 0!
  Sleep Time: 4
  Sleep Time: 4
  Sleep Time: 4
  </code></pre>
  
  <p></code></p>
  
  <p>Your help is greatly appreciated!!</p>