Wednesday, January 19, 2011

IPC using pipes-111

//1 parent and 2 child parent reads no.s and sends to childs using pipe and 1 child computes sum //of odd no.s and other child computes sum of even no.s and sends the result back to parent and //parent prints the result

#include
#include
#include
#include
#include
void main()
{ int buffer[10],temp1[10],temp2[10];pid_t childpid1,childpid2;
int pd1[2],rpd1[2],pd2[2],rpd2[2],n,no,j,st,i=0,k=0,num,sume=0,sumo=0,rsume=0,rsumo=0,tsum=0;
printf("\n enter the no of no.s(<=10)");
scanf("%d",&n);

st=pipe(pd1);
if(st==-1)
{ printf("\n unable to create pipes");
exit(0);
}
st=pipe(rpd1);
if(st==-1)
{ printf("\n unable to create pipes");
exit(0);
}
st=pipe(pd2);
if(st==-1)
{ printf("\n unable to create pipes");
exit(0);
}
st=pipe(rpd2);
if(st==-1)
{ printf("\n unable to create pipes");
exit(0);
}
childpid1=fork();
if (childpid1==0)
{ //child 1
sleep(n*3);
printf("\n child1 process computes\n ");
close(rpd1[0]);
close(pd1[1]);
read(pd1[0],temp1,sizeof(temp1));
for(i=0;i { if(temp1[i]%2==0)
sume+=temp1[i];
}
write(rpd1[1],&sume,sizeof(sume));
}

else
{
childpid2=fork();
if(childpid2==0)
{//child 2

sleep(n*3);
printf("\n child2 process computes\n ");
close(rpd2[0]);
close(pd2[1]);
read(pd2[0],temp2,sizeof(temp2));
for(i=0;i { if(temp2[i]%2!=0)
sumo+=temp2[i];
}
write(rpd2[1],&sumo,sizeof(sumo));
}

else
{//parent
close(pd1[0]);close(pd2[0]);close(rpd1[1]);close(rpd2[1]);
printf("\n parent process takes and sends nos");
k=0;
while(k { printf("\n k=%d,n=%d",k,n);
printf("\nenter no. %d ",k+1);
scanf("%d",&buffer[k]);
k++;
}
write(pd1[1],buffer,sizeof(buffer));
write(pd2[1],buffer,sizeof(buffer));
waitpid(childpid1,NULL,0);waitpid(childpid2,NULL,0);
printf("\n back to parent");
read(rpd1[0],&rsume,sizeof(int));
read(rpd2[0],&rsumo,sizeof(int));
k=0;
tsum=rsumo+rsume;
while(k {
printf("\n %d\n ",buffer[k]);

k++;
}
printf("\n sum of even no.s is %d",rsume);
printf("\n sum of odd no.s is %d",rsumo);
printf("\n sum of all no.s is %d\n",tsum);
}
}
close(pd1[0]);close(pd2[0]);close(rpd1[1]);close(rpd2[1]);
close(pd1[1]);close(pd2[1]);close(rpd1[0]);close(rpd2[0]);
}//end of main

1 comment:

  1. include"stdio.h"
    #include"sys/types.h"
    #include"unistd.h"
    #include"string.h"
    #include"stdlib.h"

    ReplyDelete