进程通信使用多个管道的互斥问题

#include<stdio.h>
  2 #include<stdlib.h>
  3 #include<sys/wait.h>
  4 #include<sys/types.h>
  5 #include<fcntl.h>
  6 #include<string.h>
  7 #include<sys/stat.h>
  8 #include<errno.h>
  9 #include<unistd.h>
 10 #include<malloc.h>
 11 #include<iostream>
 12 #include<fstream>
 13 #define FIFO1 "./fifo.1"
 14 #define FIFO2 "./fifo.2"
 15 #define MAX_BUFFER 4194304
 16 using namespace std;
 17 int main(int ac,char* av[])
 18 {
 19         FILE* query;
 20         if((query = fopen(av[1],"r")) == NULL)
 21         {
 22                 cout<<"error in opening the file"<<endl;
 23                 exit(-1);
 24         }
 25         char *a[1000000];
 26         char buf[1001];
 27         int i;
 28         for( i = 0;i < 1000000; i ++)
 29         {
 30                 a[i] = (char*)malloc(sizeof(char)*256);
 31         }
 32         i = 0;
 33         while(fgets(a[i],256,query) != NULL)
 34         {
 35                 i ++;
 36         }
 37         int len = i;
 38         int readfd1,writefd1,readfd,writefd;
 39         pid_t pid;
 40         if(mkfifo(FIFO1,S_IFIFO|0666)<0)
 41         {
 42                 printf("error in making fifo1");
 43                 exit(1);
 44         }
 45         if(mkfifo(FIFO2,S_IFIFO|0666)<0)
 46         {
 47                 printf("error in making fifo2");
 48                 exit(1);
 49         }
 50         cout<<"1<<"<<endl;
 51         if((pid = fork()) == 0)
 52         {
 53                 readfd1 = open(FIFO1, O_RDONLY);
 54                 writefd1 = open (FIFO2, O_WRONLY);
 55         //      dup2(0,readfd1);
 56                 dup2(1,writefd1);
 57                 execlp("ls","ls","-l",NULL);
 58         }
 59         cout<<"2"<<endl;
 60         writefd = open(FIFO1, O_WRONLY);
 61         readfd = open(FIFO2, O_RDONLY);
 62         //dup2(0,readfd);
 63         //dup2(1,writefd);
 64         i = 0;
 65         cout<<i<<endl;
 66         while(i < len)
 67         {
 68                 cout<<a[i];
 69                 i ++;
 70         }
 71         cout<<"hahah"<<endl;
 72         while(read(readfd,buf,1000) != 0)
 73         {
 74                 cout<<buf;
 75         }
 76         printf("succeed in asking for space\n");
 77         cout<<"~";
 78         waitpid(pid,NULL,0);
 79         close(readfd1);
 80         close(readfd);
 81         close(writefd1);
 82         close(writefd);
 83         unlink(FIFO1);
 84         unlink(FIFO2);
 85         return 0;
 86 }

上面代码中若60行与61行互换则会出现死锁问题,由于两个进程对于管道都采用的是互斥访问的策略,导致彼此都在等待对方写入数据,陷入死锁

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值