#include"kernel/types.h"
#include"kernel/stat.h"
#include"user/user.h"
const int pSize = 35;
int main(int argc, char *argvs[]){
int p[2], num, prime;
pipe(p);
if(fork() == 0){
//chPro
close(p[1]);
while(1){
//In fact, this part of program may be used by grandPro
read(p[0], &prime, sizeof(int));
if(prime!=pSize)printf("prime: %d\n",prime);
//Hard to realize is that when you repipe fd, you disconnected with
//the old pipe;
int fd[2];
pipe(fd);
//chPro pipe1 r,pipe2 rw
//chPro target: read from pipe1,write to pipe2, need p[0] fd[1] only
//prime equals pSize means the end of forking new pro, we need to exit
//this pro
if(fork() != 0 || prime == pSize){
close(fd[0]);
//if not end of pro
if(prime != pSize){
//read from pipe1 and write into pipe2
read(p[0],&num,sizeof(int));
while(num != pSize){
if(num%prime)write(fd[1],&num,sizeof(int));
read(p[0],&num,sizeof(int));
}
write(fd[1],&num,sizeof(int));
}
close(p[0]);
close(fd[1]);
//chPro detatched from pipe1 & pipe2,only wait to be exit
wait(0);
exit(0);
}
else{
//grandPro target: read from pipe2 & write to pipe3
//to reuse the program of while, redirect fd[0] to p[0]
close(p[0]);
p[0] = fd[0];
close(fd[1]);
}
}
}
else{
close(p[0]);
for(int i = 2; i <= pSize; i++)
write(p[1], &i, sizeof(int));
//Here parentPro has disconnected to pipe
wait(0);
}
exit(0);
}
【无标题】
最新推荐文章于 2024-05-19 23:47:09 发布