操作系统-请编程建立 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.

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值