What is Fork System Call?


Fork system call is used to create a child process of a process. The child process runs concurrently with the parent process. The child process has the same CPU registers, Program Counter as the parent process. The child process takes no arguments but they return integer value. Below are given different values returned by fork():

  • Negative Value : It implies that the child process was not created.
  •  0 : It implies that the child process was created successfully.
  •  Positive Value : It implies that control has returned to parent process.
Now, let's solve some output based questions on fork system calls because these questions are commonly asked in interviews, university exams or entrance exams.

1. Predict the output:

Output:
Hello world!
Hello world!

Explanation:
When fork is encountered in the above program a separate copy of this program is made. So, now we have 2 programs one which is the parent and other one which is the child. After the fork system call the parent will call the child process which will start its execution from the same spot where the parent left( after fork system call) and it will print "hello world!". When the program is terminated the control will go to the parent process again and now parent will continue its execution after fork system call and it will print "Hello world!".

2. Predict the output:

Output:
hello
hello
hello
hello
hello
hello
hello
hello

The number of times 'hello' will be printed is equal to number of process created. Thus total number of process created is 2^n where n is number of fork system calls. So,in the above case 8 times hello is printed.

Explanation:

fork(); ------------//line 1
fork(); ------------//line 2
fork(); ------------//line 3

                 L1                         //One child process created by line 1
              /       \                     
           L2       L2                   //Two child process created by line 2
         /     \      /    \
      L3    L3  L3   L3            //Four child process created by line 3


3. Predict the output:

Output:

Hello from child!
Hello from Parent!

Explanation:
When the if statement is executed then fork is called first which will create a child process and we know that when a child process is created fork returns 0 it will print "hello from child!". When control returns to parent process back fork returns a +ve value thus the else if will be executed and it will print "Hello from Parent!.
The output can also be reversed because the child and parent process are executing concurrently.

4. Predict the output:

I'm leaving this one for you guys. Give the answers in the comment section please.
I will give the answer in the next post.



Post a Comment (0)
Previous Post Next Post