#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行互换则会出现死锁问题,由于两个进程对于管道都采用的是互斥访问的策略,导致彼此都在等待对方写入数据,陷入死锁