Practical - 3
Aim- To Demonstrate process control system calls fork( )
vfork( )
wait( ) and sleep( ) getpid(
) and getppid( )
Code -
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include <sys/shm.h>
int main(){
int c;
printf("Enter : \n 1 for fork\n 2 for vfork "); scanf("%d",&c);
switch(c){
case 1:{
pid_t pid; pid
= fork();
if(pid==0){
int count=0,n; printf("Child
Process :\n");
printf("Enter numbers to check prime or not : ");
scanf("%d",&n);
printf("\nchild id - %d",getpid()); printf("\n
parent id - %d\n",getppid());
if(n==1 || n==0){
count=0;
}
for(int i=2;i<=n/2;i++){
if(n%i==0){
count++;
break;
}
}
if(count==0){
printf("Prime Number\n");
else{
printf("Not Prime\n");
}
sleep(5);
}
else{
w
a
i
t
(
)
;
i
n
t
n
1
;
printf("Parent Process :\n");
printf("Enter number to check even or odd : ");
scanf("%d",&n1);
printf("\nParent id - %d\n",getpid());
if(n1%2==0){
printf("Even Number\n");
} else{ printf("Odd
Number\n");
}
}
return 0;
} case 2:{ int a,b; int sum=0;
printf("Enter first number : ");
scanf("%d",&a); printf("Enter
second number : ");
scanf("%d",&b);
pid_t pid; pid
= vfork();
if(pid==0){
printf("Child Process :
%d\n",getpid()); sum = sum + a+ b;
printf("Sum : %d \n",sum);
}
else{
printf("Parent Process : %d\n",getpid()); sum =
sum + a+ b; printf("Sum : %d \n",sum);
}
exit(0);}
}
}
Output -