操作系统实验二之管道通信实验

设有二元函数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 <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int fx(int);
int fy(int);
int main(){
    int pid1,pid2;
    int pipe1[2],pipe2[2];
    int m,n;
    int x,y;
        printf("please enter x,y\n");
    scanf("%d%d",&x,&y);
    if(pipe(pipe1)<0){
        printf("pipe1 not created\n");
        exit(1);
    }
    if(pipe(pipe2)<0){
        printf("pipe2 not created\n");
        exit(1);
    }
    pid1 = fork();
    if(pid1<0){
        printf("process1 not created\n");
        exit(1);
    }else if(pid1==0){
        close(pipe1[0]);
        close(pipe2[0]);
        m=fx(x);
        write(pipe1[1],&m,sizeof(int));
        close(pipe1[1]);
        close(pipe2[1]);
        exit(1);
    }else{
        pid2 = fork();
        if(pid2<0){
            printf("process2 not created\n");
            exit(1);
        }else if(pid2==0){
            close(pipe1[0]);
            close(pipe2[0]);
            n=fy(y);
            write(pipe2[1],&n,sizeof(int));
            close(pipe1[1]);
            close(pipe2[1]);
            exit(1);
        }else{
            int x=0,y=0;
            close(pipe1[1]);
            close(pipe2[1]);
            read(pipe1[0],&x,sizeof(int));
            read(pipe2[0],&y,sizeof(int));
                        printf("f(x,y)=%d\n",(x+y));
            close(pipe1[0]);
            close(pipe2[0]);
        }
    }
    return 0;
}

int fx(int x){
    if(x==1){
        return 1;
    }else{
        return fx(x-1)*x;
    }
}

int fy(int y){
    if(y==1||y==2){
        return 1;
    }else{
        return fy(y-1)+fy(y-2);
    }
} 
结果:
please enter x,y 
5 10
f(x,y)=55



  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值