cforkgrandchild

Preventing grand children from forking in C


I have the following code in which I'm trying to create sub processes by forking. I want that exactly 3 sub processes are made. However, when I run the code I seem to be getting more, probably because of the children processes forking grandchildren. What am I missing here, how can I prevent this.

Code:

   for(j = 0; j < 3 ; j++){
    if((pid = fork()) == 0){            // child process
        dosomething();
        exit(0);                // terminate child process
    }
    else if((pid = fork()) > 0){
        printf("I'm in parent of the client spawn loop\n");
//      exit(0);    
    } 
}

Output:

I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop

Solution

  • Don't do the second fork call as it will create a new child. The first is enough:

    for (j = 0; j < 3; ++j)
    {
        pid_t pid = fork();
        if (pid == 0)
        {
            printf("In child (j = %d)\n", j);
            exit(0);
        }
        else if (pid > 0)
        {
            printf("In parent (j = %d)\n", j);
        }
    }
    

    Will print "In child" three times, with j equal to 0, 1 and 2. The same for the parent printing.

    In your real code you should check for errors though.