Experiment 2
Experiment 2
Subject: OS
Academic Year 2022-23
Experiment 2
Aim: Write a program to create processes in Linux using fork() system call. Hardware and
Software requirements: Linux,i386 based computers.
1. Fork(): 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.
Code 1:
#include<stdio.h>
#include <unistd.h>
int main(void)
{
int pid=fork();
if(pid == -1)
{
printf("fork failed!");
}
else if(pid == 0)
{
printf("Hello from the child process! %d\n", getpid());
}
else
{
printf("Hello from the parent process! %d\n", getppid());
}
}
Output 1:
2. wait(): The wait() system call suspends execution of the current process until one of its
children terminates. The call wait(&status) is equivalent to: waitpid(-1, &status, 0); The
waitpid() system call suspends execution of the current process until a child specified by pid
argument has changed state. If any process has more than one child processes, then after calling
wait(), parent process has to be in wait state if no child terminates.
Code 2:
#include<stdio.h>
#include <unistd.h>
int main(void)
{
int a,b,n;
pid_t ret_value;
printf("\n The process id is %d\n", getpid());
ret_value=fork();
if(ret_value<0)
{
printf("\nFork failure\n");
}
else if(ret_value == 0)
{
printf("\n******Child Process******\n");
printf("\nThe process id is %d and parent id is %d\n", getpid(),getppid());
printf("Enter a number to check even or odd\n");
scanf("%d", &n);
if(n%2==0)
printf("Number %d is even\n", n);
else
printf("number %d is odd\n", n);
sleep(20);
}
else
{
wait();
printf("Parent process\n");
printf("Process id is %d\n", getpid());
printf("Enter 2 nos. to check maximum or minimum \n");
scanf("%d%d", &a, &b);
if(a>b)
printf("%d is greater than %d\n", a, b);
else
printf("%d is greater than %d\n", b, a);
sleep(30);
}
return 0;
}
Output 2:
Conclusion: Thus we have studied that the purpose of fork() is to create a new process, which
becomes the child process of the caller. Wait functions allow a thread to block its own execution.