/* Name
: Edison Chindrawaly
* File :
parent2.c
* Date : 03/06/01
* Subj : It uses parent-child relationship to
count
* the multiple of 5 and 3 for integer of 10000
*/
#include <unistd.h>
#include
<stdio.h>
#include <stdlib.h>
#include <sys/types.h>
int
main()
{
pid_t pid;
int fd[2];
int mul5 = 0;
int
mul3 = 0;
int imul3 = 0;
int terminate = -1; // terminating
signal
int isend = 0;
int byte;
if(pipe(fd) < 0)
printf("pipe error\n");
pid = fork(); // fork the process
if(pid<0)
printf("fork
error\n");
else if(pid >
0)
{
printf("I am parent\n");
for(int i = 0; i < 10000; i++)
{
if((i%5) == 0)
mul5++;
else
byte = write(fd[1], &i, sizeof(i));
//send to child
}
write(fd[1], &terminate, sizeof(int));
printf("Multiple of 5 counted by
parent: %i \n", mul5);
printf("Parent PID: %d \n", getpid());
read(fd[0],&imul3,sizeof(int));
printf("Multiple of 3 send by child:
%i \n", imul3);
}
else
{
printf("I am child\n");
while(
(byte=read(fd[0],&isend,sizeof(int)) != 0))
{
if(isend % 3
== 0)
mul3++;
if(isend == -1)
break;
}
write(fd[1],&mul3,sizeof(int));
printf("Child PID : %d\n", getpid());
printf("Multiple of 3 counted by child
in child: %i\n",mul3);
exit(1);
}
exit(1);
}