Search code examples
cprocessforkparent

fork() in a For Loop


#include <stdio.h>
#include <sys/type.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>

int main(void)
{
    pid_t pid;
    int i;
    for(i=0; i<3; i++) {
        pid = fork();
        if(pid == -1) {
            printf("Fork Error.\n");
        } else if(pid == 0) {
            printf("I am child");
        }
    }

    if(pid != 0) {
        while((pid = waitpid(-1, NULL, 0)) > 0)
            if(errno == ECHILD)
                break;
            printf("I am parent and all children have exited.\n");
    }
    exit(0);

    return 0;
}

The result is that,

'I am child' is printed 7 times, 'I am parent and all children have exited.' is printed 4 times

and the print sequence is not fixed.

Here's my question!

Why 'I am child' is printed 7 times,

and 'I am parent and all children have exited.' is printed 4 times ?

I don't understand the number of times those sentences are printed.

Could you explain it in detail?


Solution

  • You can try the code below. You need to add the wait header. At the same time, after providing the 0 condition of the child processes, you should definitely sign out, otherwise each processes will fork again and again each time in the code. Shortly you have to kill every process after their task end.

    #include <stdio.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <sys/wait.h>
    
    int main(void){
    
        pid_t pid;
        int i;
    
        for (i = 0; i < 3; i++)
        {
            pid = fork();
    
            if (pid == -1) {
    
                printf("Fork Error.\n");
    
            } else if (pid == 0) {
                printf("I am child\n");
                exit(0); // !
            }
        }
    
        if (pid != 0) {
    
            while ((pid = waitpid(-1, NULL, 0)) > 0)
                if (errno == ECHILD)
                    break;
    
            printf("I am parent and all children have exited.\n");
        }
    
        return 0;
    }