Monday, 2 December 2013

X sends N numbers to Y who select prime numbers and send them to Z. Z send the sum of primes to X who displays the result. Implement IPC using pipes. X,Y,Z are processes.

#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
int pid,pid1,p[2],p2[2],p3[2],buff1[100],buff2[100],i,n,n2,num,check,a,j;
int sum=0;
printf("Enter limit : ");
scanf("%d",&n);
n2=0;
a = pipe(p);
if(a==-1)
{
perror("error pipe 1");
exit(1);
}
a = pipe(p2);
if(a==-1)
{
perror("error pipe 2");
exit(1);
}
a = pipe(p3);
if(a==-1)
{
perror("error pipe 3");
exit(1);
}
pid = fork();
switch(pid)
{
case -1: perror("fork");
exit(1);
break;
case 0: n2 = read(p2[0],buff2,sizeof(buff2));
printf("In child process Z (PID : %d ) \n",pid);
n2 = n2/sizeof(int);

printf("value of n2: %d",n2);
for(i=0;i<n2;i++)
{
printf("\nPrime numbers %d : %d",i+1,buff2[i]);
sum = sum + buff2[i];
}
buff1[0] = sum;
write(p3[1],buff1,sizeof(int));
exit(1);
break;

default:
pid1 = fork();
switch(pid1)
{
case -1: perror("fork");
exit(1);
break;

case 0 :
read(p[0],buff2,sizeof(buff2));
printf("In child process Y (PID1 : %d ) \n",pid1);
for(i=0;i<n;i++)
{
int flag=1;
num = buff2[i];
if(num < 2)
{
flag=0;
}
else
{
check = sqrt(num);
for(j=2;j<=check;j++)
{
if(num%j == 0)
{
flag=0;
break;
}
}
}
if(flag==1)
{
buff1[n2] = num;
n2++;
}
}
write(p2[1],buff1,n2*sizeof(int));
exit(1);
break;
default: printf("In parent process X (PID: %d) \n",pid1);
for(i=0;i<n;i++)
{
printf("enter element %d : ",i+1);
scanf("%d",&buff1[i]);
}
write(p[1],buff1,n*sizeof(int));
waitpid(pid1,NULL,0);
printf("\nIn parent process (PID: %d) \n",pid1);
read(p3[0],buff2,sizeof(buff2));
printf("\nsum : %d\n",buff2[0]);
}
break;
}
close(p[0]);
close(p[1]);
close(p2[0]);
close(p2[1]);
close(p3[0]);
close(p3[1]);
return 0;
}


OUTPUT:
$ gcc program.c -lm -o prog (NOTE: -lm is important to compile math functions like sqrt)
$ ./prog

Enter limit : 3
In parent process X (PID: 4773)
enter element 1 : 1
enter element 2 : 2
enter element 3 : 5
In child process Y (PID1 : 0 )
In child process Z (PID : 0 )
value of n2: 2
Prime numbers 1 : 2
Prime numbers 2 : 5
In parent process (PID: 4773)
sum : 7

No comments:

Post a Comment