0

I am trying to create number of processes that I desire, for example, 4 child processes. I tried the for loop, however, it only print out 1 child process. Please be advised

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int
main(int argc, char *argv[])
{
    printf("HHHHHhello world (pid:%d)\n", (int) getpid());
    int rc = fork();
    int i;
for (i = 0; i <3 ; i ++)
 {
    if (rc < 0) {
        // fork failed; exit
        fprintf(stderr, "fork failed\n");
        exit(1);
    } else if (rc == 0) {
        // child (new process)
        printf("hello, I am child (pid:%d)\n", (int) getpid());
        sleep(1);

    } 
      else {
        // parent goes down this path (original process)
        int wc = wait(NULL);
        printf("hello, I am parent of %d (wc:%d) (pid:%d)\n",
               rc, wc, (int) getpid());
    }

    return 0;
}
}
  • 3
    You only call `fork` once before the loop, and you `return` at the end of the loop so it would only execute once. – dbush Feb 13 '20 at 05:06
  • 1
    May be a duplicate Question for this(https://stackoverflow.com/questions/6542491/how-to-create-two-processes-from-a-single-parent), or [this] (https://stackoverflow.com/questions/13152415/run-a-child-form-process-from-parent-in-c-sharp) or this (https://stackoverflow.com/questions/876605/multiple-child-process) – Vikrant Jain Feb 13 '20 at 05:08
  • @dbush ok so I put the rc =fork() inside the for loops, it actually print out the child process. however it printout more than 4 child process and the parent even printed out before the other child process finish. – Lan Nguyen Feb 13 '20 at 05:48

0 Answers0