1. 程式人生 > >作業系統-請程式設計建立 3 個併發協作程序,它們分別完成 f(x,y)、f(x)、f(y)

作業系統-請程式設計建立 3 個併發協作程序,它們分別完成 f(x,y)、f(x)、f(y)

我的程式碼

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int f1(int x)
{
  if(x==1)
  {
   return 1;
  }
  else
  {
    return f1(x-1)*x;
  }
}
int f2(int y)
{
  if(y ==1||y==2)
  {
    return 1;
  }
  else
  {
     return f2(y-1)+f2(y-2);
  }
}
int main(int argc,char* argv[])
{
   int
x,y; printf("Input x,y\n"); scanf("%d %d",&x,&y); int pid1,pid2; int pipe1[2]; int pipe2[2]; int pipe3[2]; int pipe4[2]; if(pipe(pipe1)<0) { printf("pipe1 error"); } if(pipe(pipe2)<0) { printf("pip2 error"); } if(pipe(pipe3)<0) { printf
("pipe3 error"); } if(pipe(pipe4)<0) { printf("pipe4 error"); } if((pid1=fork())<0) { perror("pipe not create"); } else if(pid1==0) { close(pipe1[1]); close (pipe2[0]); int x1; read(pipe1[0],&x1,sizeof(int)); int z=f1(x1); write(pipe2[1],&z,sizeof(int
)); close(pipe1[0]); close(pipe2[1]); exit(0); } else { //Father process if((pid2=fork())<0) { perror("Process not create "); exit(EXIT_FAILURE); } else if(pid2==0) { close(pipe3[1]); close(pipe4[0]); int y1; read(pipe3[0],&y1,sizeof(int)); int z=f2(y1); write(pipe4[1],&z,sizeof(int)); close(pipe3[0]); close(pipe4[1]); exit(0); } close(pipe1[0]); close(pipe2[1]); close(pipe3[0]); close(pipe4[1]); int z; write(pipe1[1],&x,sizeof(int)); write(pipe3[1],&y,sizeof(int)); read(pipe2[0],&x,sizeof(int)); read(pipe4[0],&y,sizeof(int)); z=x+y; printf("the result is %d\n",z); close(pipe1[1]); close(pipe2[0]); close(pipe3[1]); close(pipe4[0]); } return 0; }

原理利用四個管道進行通訊,注意管道是單向的,由父程序傳x,y到子程序,同理子程序傳相應結果;

相關資料

管道 pipe 是程序間通訊最基本的一種機制,兩個程序可以通過管道一個在管道
一端向管道傳送其輸出,給另一程序可以在管道的另一端從管道得到其輸入.管道以
半雙工方式工作,即它的資料流是單方向的.因此使用一個管道一般的規則是讀管道
資料的程序關閉管道寫入端,而寫管道程序關閉其讀出端.
1)pipe 系統呼叫的語法為:

#include <unistd.h>
int pipe(int pipe_id[2]);

如果 pipe 執行成功返回 0, pipe_id[0]中和 pipe_id[1]將放入管道兩端的描述符.
出錯返回-1.