1

So here is my code that will take an int as an command line argument then fork N child processes (That run simultaneously). And then when each child ends, the parent will echo the child that child exit status.

But right now I can only do child by child but not simultaneously. How can I do it?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>

int main ( int argc, char *argv[] )
{
    int i, pid, ran;

    for(i = 0; i < atoi(argv[1]); i++) {
    pid = fork();
    srand(time(NULL));
    ran = (rand() % 10) + 1 ;

     if (pid < 0) {
        printf("Error");
        exit(1);
     } else if (pid == 0) {
        printf("Child (%d): %d\n", i + 1, getpid());
        printf("Sleep for = %d\n", ran);
        sleep(ran);
        exit(ran); 
     } else  {
        int status = 0;
        pid_t childpid = wait(&status);
        printf("Parent knows child %d is finished. \n", (int)childpid);
     }
  }

}

Nelson Tang
  • 41
  • 1
  • 5
  • 2
    Possible duplicate of [How to run two child processes simultaneously in C?](http://stackoverflow.com/questions/7479194/how-to-run-two-child-processes-simultaneously-in-c) – Rahul Jha Oct 09 '15 at 20:28
  • the function: `srand()` should only be called once, not every time through the loop – user3629249 Oct 11 '15 at 18:08
  • before using `argv[1]`, the code needs to compare `argc` with 2 to assure the `argv[1]` parameter exists, if `argc` is < 2 then output a 'usage' message and exit – user3629249 Oct 11 '15 at 18:10
  • the code does not compile cleanly. it is missing `#include ` and `#include ` Always enable all warnings when compiling (for gcc, at a minimum use: `-Wall -Wextra -pedantic` ) – user3629249 Oct 11 '15 at 18:23
  • Please indent the code consistently. That makes is much easier to read/understand by us humans – user3629249 Oct 11 '15 at 18:24

1 Answers1

3

You're calling wait() inside of the loop where you're spawning the children, so it won't continue the loop to start the next child until the current one is done.

You need to call wait() outside of the loop in a separate loop:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>

int main ( int argc, char *argv[] )
{
    int i, pid, ran;

    for(i = 0; i < atoi(argv[1]); i++) {
        pid = fork();
        srand(time(NULL));
        ran = (rand() % 10) + 1 ;

         if (pid < 0) {
            printf("Error");
            exit(1);
         } else if (pid == 0) {
            printf("Child (%d): %d\n", i + 1, getpid());
            printf("Sleep for = %d\n", ran);
            sleep(ran);
            exit(ran); 
         }
    }

    for(i = 0; i < atoi(argv[1]); i++) {
        int status = 0;
        pid_t childpid = wait(&status);
        printf("Parent knows child %d is finished. \n", (int)childpid);
    }
}
dbush
  • 205,898
  • 23
  • 218
  • 273