CC311_Lab4
CC311_Lab4
Lab Summary
We will study syntax, working and usage of fork () system call
in this lab.
#include<unistd.h>
pid_t fork(void);
the child gets its program? The child runs the same code as its
parent; hence, it is called a duplicate process.
If the same code is run both by the parent and the child then isn’t
the task done twice? It’s the job of the programmer to write the
code in such a manner that only one of the task is done when the
parent process runs the code and the other task is done when the
child runs the code.
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t p;
printf("before fork\n");
p=fork();
if(p==0)
{
printf("I am child having id %d\n",getpid());
printf("My parent's id is %d\n",getppid());
}
else
{
printf("My child's id is %d\n",p);
printf("I am parent having id %d\n",getpid());
}
printf("Common\n");
}
Hence the next lines of code has been written to check the value
of ‘p’. When the if-else code runs from within the parent the
condition becomes false and the else part is run. So, the lines
My child’s id is 28
I am parent having id 27
When the if-else case runs from within the child the if condition
becomes true and hence the lines
I am child having id 28
My parent’s id is 27
Since the printf(“common\n”) line was out of the if-else it has been
printed twice; once by the parent process and once by the child
process.
Point to Remember:
If the code is run multiple times, the order of the output lines may
differ. Since there are two processes, the processor can be
assigned to any of them. One of them can pre-empt the other and
hence the output may overlap. The order of the output will differ. If
you want the parent to execute first or the child to execute first
then either wait() or sleep() functions can be used depending on
the requirement.
Q1. Write a program using fork() system call to create two child of
the same process i.e., Parent P having child process P1 and P2.
Q2. Write a program using fork() system call to create a hierarchy
of 3 process such that P2 is the child of P1 and P1 is the child of
P.
int main()
{
fork();
fork();
}