Illustration of Fork() system call

Consider the following pseudo-code

    int t1 = 0, t2 = 0, t3 = 0;
    t1 = fork();
    t2 = fork();
    if (t1 != 0) {
        t3 = fork();

What is the total number of processes created by execution of this above program?

If you are not familiar how the fork() system call works, please refer to this link :

Lets clarify each thing carefully. I will be enumerating fork calls as 1st ,2nd and 3rd in order. 1st I will tell u execution of parent only.

Parents: When the parent excutes 1st fork, parent's t1 will receive PID1 which is non zero, whereas Child C1's t1 will be having 0 and all children of C1 will use t1=0.

When parent executes 2nd fork,parent's t2=PID2, child C2 will be created and it will have value of t2=0.parent's t1 will be PID1 which will be passed to C2.

Now parent's t1 =PID1 which is non zero ,so it will execute 3rd fork and create process C3. t3 of parent will be PID3 and non zeros,where as C3's t3 will be Zero.


Now turning to children's fork execution part,C1 will execute fork and create process C11. C1 's t2 will be PID11 and non zero whereas C11's t2 will be zero.

It is worth remembering that C1 and C11 will be using value of t1 of C1 ,which is zero, so neither of them will be able to execute 3rd fork which is inside "if" clause. they will not call neither fork nor print and they terminate. Here we count 2 processes. C1 and C11 C2 is having t1=PID1 which is non zero, whereas its t2=0.

Now C2 will be able to execute 3rd fork and create process C21. C2's t3 = PID21 non zero,whereas C21's t3 =0. Now C21 will call print function and terminate. same with we count 2 processes C2 and C21.

Total process , Parent, C1,C2,C3, C11,C21 = 6.

RAHUL TIWARI rtiwari95 7 Dec 2016 12:27 pm

6 processes will be created here.

Rahul rahul55523 11 Jan 2017 08:37 pm

nice one 


Ajith Supramani ajithsupramani 12 Jan 2017 11:04 am


Abhinav Arora abhinav93 20 Jan 2017 11:34 am

Why are we counting the parent process it is already given to us?