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

设有二元函数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 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



你可能感兴趣的:(操作系统,C)