PIPE
- 匿名管道,用于父子进程或者亲戚进程之间的通信
- 函数
int pipe(int fd[2])
- 头文件
#include <unistd.h>
- 实现代码
复制代码
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#include <unistd.h> #include <iostream> #include <string.h> using namespace std; int main() { int pid = fork(); int fd[2]={0}; if (pipe(fd) < 0){ cout << "pipe error" << endl; return -1; } char buf[128] {0}; cout << "pid:" << pid << ";" << fd[0] << ";" << fd[1] << endl; if (pid > 0) { // 父进程 close(fd[1]); // 关闭写端 cout << "等待子进程输入" << endl; read(fd[0], buf, 128); cout << "子进程输入: " << buf << endl; close(fd[0]); } else if (pid == 0) { // 子进程 close(fd[0]); // 关闭读端 sleep(1); sprintf(buf, "hello"); cout << "子进程输入" << buf << endl; write(fd[1], buf, sizeof(buf)); // close(fd[1]); } else { cout << "fork error" << endl; return -1; } if (pid > 0) { // 等待子进程结束 int status; waitpid(pid, &status, 0); } return 0; }
- 代码实现的是子进程输入,父进程输出。
- 几个问题
- 为什么要在进入子进程的时候关闭读端,进入父进程的时候关闭写端。
可以查看cout << "pid:" << pid << ";" << fd[0] << ";" << fd[1] << endl;
。不关事子进程还是父进程对于fd的输出是一致的。产生这种写过的原因是pipe函数在父子进程之间创建的机制决定的 - 为什么子进程关闭了读端,父进程还能读取。父进程关闭了写端,子进程还能写入。
这个其实和共享指针类似,Linux系统对于fd描述符的拷贝也是存在一个计数器,,每次close只是将计数器减1,直到计数器为0才是真实的关闭。
最后
以上就是传统戒指最近收集整理的关于Linux C++ 进程间通信-PIPEPIPE的全部内容,更多相关Linux内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复