Fork System Call

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

fork() in C

Fork system call is used for creating a new process, which is called child process, which runs
concurrently with the process that makes the fork() call (parent process). After a new child
process is created, both processes will execute the next instruction following the fork() system
call. A child process uses the same pc(program counter), same CPU registers, same open files
which use in the parent process.

It takes no parameters and returns an integer value. Below are different values returned by fork().

Negative Value: creation of a child process was unsuccessful.


Zero: Returned to the newly created child process.
Positive value: Returned to parent or caller. The value contains process ID of newly created child
process.

Please note that the above programs don’t compile in Windows environment.

1. Predict the Output of the following program:.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
  
    // make two process which run same
    // program after this instruction
    fork();
  
    printf("Hello world!\n");
    return 0;
}

2. Output:
3. Hello world!
4. Hello world!

Calculate number of times hello is printed:

#include <stdio.h>
#include <sys/types.h>
int main()
{
    fork();
    fork();
    fork();
    printf("hello\n");
    return 0;
}

5. Output:
6. hello
7. hello
8. hello
9. hello
10. hello
11. hello
12. hello
13. hello

The number of times ‘hello’ is printed is equal to number of process created. Total Number
of Processes = 2n, where n is number of fork system calls. So here n = 3, 23 = 8

Let us put some label names for the three lines:

fork (); // Line 1


fork (); // Line 2
fork (); // Line 3

L1 // There will be 1 child process


/ \ // created by line 1.
L2 L2 // There will be 2 child processes
/ \ / \ // created by line 2
L3 L3 L3 L3 // There will be 4 child processes
// created by line 3
So there are total eight processes (new child processes and one original process).

If we want to represent the relationship between the processes as a tree hierarchy it would be
the following:

The main process: P0


Processes created by the 1st fork: P1
Processes created by the 2nd fork: P2, P3
Processes created by the 3rd fork: P4, P5, P6, P7

P0
/ | \
P1 P4 P2
/ \ \
P3 P6 P5
/
P7

Lab Task:
Submit the two examples of fork system call of your choice with
description and screenshot of running code.

You might also like