OS Lab Manual Part 3
OS Lab Manual Part 3
Objective:
Process basics: Creating processes using fork()
Description:
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().
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
Output:
Hello world!
Hello world!
#include <stdio.h>
#include <sys/types.h>
int main()
{
fork();
fork();
fork();
printf("hello\n");
return 0;
}
Output:
hello
hello
hello
hello
hello
hello
hello
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:
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:
P0
/ | \
P1 P4 P2
/ \ \
P3 P6 P5
/
P7
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void forkexample()
{
// child process because return value zero
if (fork() == 0)
printf("Hello from Child!\n");
Output:
1.
Hello from Child!
Hello from Parent!
(or)
2.
Hello from Parent!
Hello from Child!
Important: Parent process and child process are running the same program, but it does not mean they are
identical. OS allocate different data and states for these two processes, and the control flow of these processes
can be different. See next example:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void forkexample()
{
int x = 1;
if (fork() == 0)
printf("Child has x = %d\n", ++x);
else
printf("Parent has x = %d\n", --x);
}
int main()
{
forkexample();
return 0;
}
Output:
Parent has x = 0
Child has x = 2
(or)
Child has x = 2
Parent has x = 0
Here, global variable change in one process does not affected two other processes because data/state of two
processes are different. And also parent and child run simultaneously so two outputs are possible.
fork() vs exec()
The fork system call creates a new process. The new process created by fork() is a copy of the current process
except for the returned value.
The exec() system call replaces the current process with a new program.
Exercise:
printf("forked\n");
return 0;
}