Ria
Ria

Reputation: 467

Need help understanding fork C++

I am trying to create a program that uses fork to create 4 processes, which I am understanding to be 2 parents and 2 children.

The way I have set up my code is:

for(int i = 0; i < 2; ++i){
     pid_t pid1 = fork();
     switch(pid1){
        case -1:
            fatal("fork failed");
            break;
        case 0:
            child(i);
            break;
        default:
           parent(i);
           break;
     }
}

In child() and parent() respectively, I am calling getpid(). Inside child(), I exit(0) once I am done. Inside parent() I wait for the child using wait(0) When I run the program, it outputs 2 different children pids and 2 same parent pids. Is this happening because I am calling the same fork() twice?

Upvotes: 1

Views: 548

Answers (2)

Aisha Javed
Aisha Javed

Reputation: 169

Because you have used exit function in child(i) function, child will exit and hence only parent process will continue it's execution in for loop. So you only get 2 new process forked which are childs of same parent . So parent id stays same but since two childs are created, so get 2 distinct child pids! If you want four process to be forked, then you will have to erase the exit statement from child(i) function and use if else statements after each fork() call.

Upvotes: 0

hyde
hyde

Reputation: 62777

  1. Process 1 calls fork for 1st loop iteration, creating process 1.1.

  2. Then process 1 calls fork again for 2nd loop iteration, creating process 1.2.

  3. Then process 1.1 (which is essentially process 1 duplicated when fork was done) also enters 2nd loop iteration, creating process 1.1.1.

So processes 1.1 and 1.2 have same parent, process 1. And there are total 4 processes (1, 1.1, 1.2, 1.1.1).

Note that steps 2 and 3 may happen in different order, depending on how OS decides to schedule processes.

Upvotes: 2

Related Questions