pipe函数建立的管道实际上是个匿名管道,由内核负责维护的一块存储区域。半双工通信,而且只能用于共同祖先进程之间。通过FIFO,不相关的进程也能交换数据。FIFO实际上是一种文件类型,打开的描述符号可以读写(two-way双工)。
复制代码
1
2
3
4
5
6#include <sys/types.h> #include <sys/stat.h> int mkfifo(const char *pathname, mode_t mode); 返回值: 成功返回0,出错返回-1
mode参数可由以下常量(定义于fcntl.h)通过逻辑位或逻辑构成。
复制代码
1
2
3
4
5
6
7
8
9
10O_RDONLY 只读模式 O_WRONLY 只写模式 O_RDWR 读写模式 O_APPEND 每次写操作都写入文件的末尾 O_CREAT 如果指定文件不存在,则创建这个文件 O_EXCL 如果要创建的文件已存在,则返回 -1,并且修改 errno 的值 O_TRUNC 如果文件存在,并且以只写/读写方式打开,则清空文件全部内容(即将其长度截短为0) O_NOCTTY 如果路径名指向终端设备,不要把这个设备用作控制终端。 O_NONBLOCK 如果路径名指向 FIFO/块文件/字符文件,则把文件的打开和后继 I/O
以下三个常量同样是选用的,它们用于同步输入输出
复制代码
1
2
3O_DSYNC 等待物理 I/O 结束后再 write。在不影响读取新写入的数据的前提下,不等待文件属性更新。 O_RSYNCread等待所有写入同一区域的写操作完成后再进行 O_SYNC 等待物理 I/O 结束后再write,包括更新文件属性的 I/O
不同祖先进程的通信
进程A
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> main() { int r; int fd; int num = 0; r = mkfifo("mypipe", 0666); if (r < 0) perror("mkfifo error"), exit(-1); fd=open("mypipe",O_RDWR); if (fd < 0) perror("open error"), exit(-1); while(1) { r = write(fd, &num, 4); if (r < 0) perror("write error"), exit(-1); printf("发送:%dn", num); num++; sleep(1); } }
进程B
复制代码
执行效果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> main() { int fd; int buf; int r; fd = open("mypipe", O_RDWR); if (fd == -1) perror("open error"), exit(-1); while(1) { r = read(fd, &buf, 4); if (r <= 0) perror("read error"), exit(-1); printf("接收:%dn", buf); sleep(1); } }
父子进程之间
复制代码
执行效果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> main() { int r; int fd; int num = 0; int buf; pid_t pid; r = mkfifo("mypipe", 0666); if (r < 0) perror("mkfifo error"), exit(-1); pid = fork(); if (pid < 0) perror("fork error"), exit(-1); if (pid == 0) { fd = open("mypipe", 0666); if (fd < 0) perror("child open error"), exit(-1); while(1) { r = write(fd, &num, 4); if (r < 0) perror("write error"), exit(-1); num++; sleep(1); } } else { fd = open("mypipe", 0666); if (fd < 0) perror("parent open error"), exit(-1); while(1) { r = read(fd, &buf, 4); if (r < 0) perror("read error"), exit(-1); printf("父进程读取:%dn", buf); sleep(1); } } }
最后
以上就是激昂草莓最近收集整理的关于linux进程间通信之实名管道的全部内容,更多相关linux进程间通信之实名管道内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复