Points To Catch
- When we fork in any process it simply creates a copy of the same process which we call child process
Fork returns 0 in the child process & PID of the child process in the parent process, which you can see in above example. returns -1 on failer.
- Create copy of process including memory variables & stored value in it with its own address space
Example 1
|
|
Output
Example 2
How many process this program create?
Answer = 6
Explanation :
- In Parent process(P), i = 0. we create 1 child process(C1), both entering the loop at i = 1. Total = 2 processes.
- In Parent(P) & Child(C1) process, i = 1. Both of those processes fork & let say create C2 & C3, but none of them continue to iterate because of the
if (fork() && (i == 1)) break;
line. Total = 4 processes, but only two of those are continuing to loop. - In Child(C2) & Child(C3) process, i = 2. Both fork & let say create C4 & C5, resulting in 6 processes.
- In Child(C4) & Child(C5) process, i = 3. Exit the loop (since i < 3 == false , there is no more looping)