Linux编程基础之管道通信

管道是进程通信的一种方式,它可以满足两个进程之间传递数据(可以一次性也可以满足连续传输),它可以分无名管道和命名管道两种,它具有下面几个特点:

1)可以看作是个单向的数据结构,一个进程(写进程)从管道尾部写入数据,另一个进程(读进程)从管道头部读取数据。

2)具有流控制机制,读进程发现管道为空时,会阻塞,同样,写进程发现管道已满时,会阻塞。

3)管道可以用文件操作的API来处理,特别是命名管道在文件系统中是真实存在的,并共用命令空间。

具体知识可参照下图

Linux编程基础之管道通信_第1张图片

 

代码示例:pipe.c

 1 #include <unistd.h>
2 #include <stdlib.h>
3 #include <errno.h>
4 #include <string.h>
5 #include <stdio.h>
6 /***********************************************************
7 功能说明:无名管道的编程
8 author: [email protected]
9
10 ***********************************************************/
11
12 int main(int argc, char * argv[])
13 {
14
15 int files[2];
16
17 int r = pipe(files); //需要在fork之前生成这个管道,以便子进程可以直接继承该文件描述符。
18
19 pid_t pid = fork();
20
21 if(pid<0)
22 {
23 printf("fork error for %m\n",errno );
24 }else if(pid == 0)
25 {
26 //子进程写入管道
27 char *str = "hello pipe from child";
28 int r = write(files[1], str, strlen(str));
29
30 sleep(3);
31 str = "sleep end";
32 r = write(files[1],str,strlen(str));
33
34 close(files[1]);
35 close(files[0]);
36
37 }else
38 {
39 //父进程读取管道
40 char buf[512];
41
42 int rn = read(files[0], buf, 512);
43
44 printf("parent read1:%s\n", buf);
45
46 sleep(4);
47 rn = read(files[0], buf, 512);
48 printf("parent read2:%s\n", buf);
49 close(files[0]);
50 close(files[1]);
51 wait(NULL);
52
53
54 }
55
56
57
58
59 }


运行结果:

你可能感兴趣的:(linux)