管道:俩个进程间进行单向通信的机制;pipe:无名管道 :父子进程;pipe[0]写端;pipe[1]读端;命名管道:无关系进程;
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<string.h>
4 #include<unistd.h>
5
6 int main()
7 {
8 char *parent_talk[] = {"Hello", "Can you tell me, what is time?","OMG, i have to go. Bye.",NULL};
9 char *child_talk[] = {"Hi","No problem.","See you Again.",NULL};
10
11 int fd1[2];
12 int fd2[2];
13
14 int res = pipe(fd1);
15 if(res == -1)
16 {
17 printf("create pipe1 error.\n");
18 exit(1);
19 }
20 res = pipe(fd2);
21 if(res == -1)
22 {
23 printf("create pipe2 error.\n");
24 exit(1);
25 }
26
27 pid_t pid;
28 pid = fork();
29 if(pid == 0) //child
30 {
31 close(fd1[1]);
32 close(fd2[0]);
33
34 char buf[256];
35 int i = 0;
36 char *talk = child_talk[i];
37 while(talk != NULL)
38 {
39 sleep(5);
40 read(fd1[0],buf, 256);
41 printf("Parent:> %s\n",buf);
42 write(fd2[1],talk, strlen(talk)+1);
43 i++;
44 talk = child_talk[i];
45 }
46
47 close(fd1[0]);
48 close(fd2[1]);
49 }
50 else if(pid > 0)//parent
51 {
52 close(fd1[0]);
53 close(fd2[1]);
54
55 char buf[256];
56 int i = 0;
57 char *talk = parent_talk[i];
58 while(talk != NULL)
59 {
60 write(fd1[1], talk, strlen(talk)+1);
61 read(fd2[0],buf,256);
62 printf("Child:> %s\n",buf);
63 i++;
64 talk = parent_talk[i];
65 }
66
67 close(fd1[1]);
68 close(fd2[0]);
69 int status;
70 wait(&status);
71 }
72
73 return 0;
74 }