實驗二:進程通訊實驗

來源:互聯網
上載者:User

實驗要求

設有二元函數 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

實驗結果


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.