线程和管道通信实验(山东大学操作系统实验)

设有二元函数f(x,y) = f(x) + f(y) 其中: f(x) = f(x-1) * x (x >1) f(x)=1 (x=1) f(y) = f(y-1) + f(y-2) (y> 2) f(y)=1 (y=1,2) 请编程建立3个并发协作进程或线程,它们分别完成f(x,y)、f(x)、f(y)


代码如下:​​


#include


#include


#include


int main(void){


int pid1,pid2;


int pipex1[2];


int pipex2[2];


int pipey1[2];


int pipey2[2];


int x,y;


if(pipe(pipex1)<0){


perror("pipe not create!");


exit(EXIT_FAILURE);}


if(pipe(pipex2)<0){


perror("pipe not create!");


exit(EXIT_FAILURE);}


if(pipe(pipey1)<0){


perror("pipe not create!");


exit(EXIT_FAILURE);}


if(pipe(pipey2)<0){


perror("pipe not create!");


exit(EXIT_FAILURE);}


if((pid1=fork())<0){


perror("process1 not create!");}


else if(pid1==0){


int i=1;


int sum=1;


printf("childx process id:%d\n",getpid());


close(pipex1[1]);


close(pipex2[0]);


read(pipex1[0],&x,sizeof(int));


if(x<=0){printf("errorx!\n");


exit(0);}


while(i<=x)


{sum*=i++;}


x=sum;


write(pipex2[1],&x,sizeof(int));


close(pipex1[0]);


close(pipex2[1]);}


if(pid1>0){


pid2=fork();


if(pid2<0){


perror("process not create!");


exit(EXIT_FAILURE);}


if(pid2==0){


printf("childy process id:%d\n",getpid());


close(pipey1[1]);


close(pipey2[0]);


read(pipey1[0],&y,sizeof(int));


if(y<0){printf("errory!\n");


exit(0);}


int f1=1;


int f2=1;


int f3;


int j=3;


if(y<=2){


f3=f1;}


while(j<=y){


f3=f1+f2;


f1=f2;


f2=f3;


j++;}


y=f3;


write(pipey2[1],&y,sizeof(int));}


if(pid2>0){


printf("parent process id:%d\n",getpid());


printf("please enter x,y:\n");


scanf("%d,%d",&x,&y);


close(pipex1[0]);


close(pipex2[1]);


close(pipey1[0]);


close(pipey2[1]);


write(pipex1[1],&x,sizeof(int));


write(pipey1[1],&y,sizeof(int));


sleep(1);


read(pipex2[0],&x,sizeof(int));


read(pipey2[0],&y,sizeof(int));


int sum1=x+y;


printf("f(x)=%d\n f(y)=%d\n f(x,y)=%d\n",x,y,sum1);


waitpid(pid1,NULL,0);


waitpid(pid2,NULL,0);}}}​


运行结果如下:

你可能感兴趣的:(操作系统学习)