实验二:进程通信实验

来源:互联网 发布:焉知冷暖萧繁华和左 编辑:程序博客网 时间:2024/05/04 23:59

实验要求

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


实验代码

/* *exp2.c */#include<stdio.h>#include<stdlib.h>#include<unistd.h>int calcfy(int y){  if(y==1||y==2){    return 1;  }else{    return calcfy(y-1)+calcfy(y-2);  }}int main(int argc,char *argv[]){  int pid1;  int pid2;  int pipe1[2];  int pipe2[2];  printf("Please input x y:");  int x,y;  scanf("%d %d",&x,&y);  printf("x=%d, y=%d\n",x,y);  if(x<1||y<1){    perror("bad input\n");    exit(EXIT_FAILURE);  }  if(pipe(pipe1)<0){    perror("pipe not create");    exit(EXIT_FAILURE);  }  if(pipe(pipe2)<0){    perror("pipe not create");    exit(EXIT_FAILURE);  }  pid1=fork();  if(pid1<0){    perror("process not create\n");    exit(EXIT_FAILURE);  }else if(pid1==0){    int fx;    close(pipe1[0]);    for(fx=1;x>1;x--){      fx*=x;    }    write(pipe1[1],&fx,sizeof(int));    close(pipe1[1]);  }else{    pid2=fork();    if(pid2<0){      perror("process not create\n");      exit(EXIT_FAILURE);    }else if(pid2==0){      int fy;      close(pipe2[0]);      fy=calcfy(y);      write(pipe2[1],&fy,sizeof(int));      close(pipe2[1]);    }else{      int fx,fy;      read(pipe1[0],&fx,sizeof(int));      read(pipe2[0],&fy,sizeof(int));      printf("I'm %d\n",getpid());      printf("Get fx=%d from %d\n",fx,pid1);      printf("Get fy=%d from %d\n",fy,pid2);      printf("f(x,y)=%d\n",fx+fy);      return EXIT_SUCCESS;    }  }}  

#makefilecc=gccsrc=exp2.cobj=exp2.oexp2:$(obj)$(cc) $(obj) -o $@exp2.o:$(cc) -c $(src)clean:rm *.o

实验结果


原创粉丝点击