Fork System Call
Fork System Call
Fork System Call
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().
Please note that the above programs don’t compile in Windows environment.
#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!
#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
If we want to represent the relationship between the processes as a tree hierarchy it would be
the following:
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.