当前位置:网站首页>进程间通信方式(1)无名管道(全CSDN最用心的博主)
进程间通信方式(1)无名管道(全CSDN最用心的博主)
2022-08-11 01:22:00 【畅畅ccc】
在前几篇文章当中我们为大家详细的讲述了进程和线程基本和进阶应用,那么不同的进程和线程当中如果我们进行数据的交互,或者信息的访问,我们应该采取什么办法呢?
那么本文将为大家讲述进程间的通信方式-----管道中的无名管道
管道分为无名管道和有名管道
- 无名管道 ===》pipe ==》只能给有亲缘关系进程通信
- 有名管道 ===》fifo ==》可以给任意单机进程通信
管道的特性:
- 管道是 半双工的工作模式
- 所有的管道都是特殊的文件不支持定位操作。(lseek->> fd fseek ->>FILE* )
- 管道是特殊文件,读写使用文件IO。(open,read,write,close)
使用框架:
- 创建管道 == 》 读写管道 ==》关闭管道
1.创建管道
int pipe(int pipefd[2]);
- 功能:创建并打开一个无名管道
- 参数:
- pipefd[0] ==>无名管道的固定读端
- pipefd[1] ==>无名管道的固定写端
- 返回值:
- 成功 0
- 失败 -1
2.读写管道
把pipefd当作文件描述符进行操作,pipefd[0] ==>无名管道的固定读端,pipefd[1] ==>无名管道的固定写端,pipefd的位置是固定的,在使用时要记得
3.关闭管道
close pipefd[0];
close pipefd[1];
关闭管道也没有特殊的函数接口,和关闭文件描述符一样,在文件IO的操作里运用close的指令操作。
代码示例:
int main(int argc, const char *argv[]) { int pipefd[2]; int ret = pipe(pipefd); if(ret < 0) { perror("fail to pipe\n"); return -1; } pid_t pid = fork(); if(pid > 0) { close(pipefd[0]); while(1) { char buff[1024] = {0}; fgets(buff, sizeof(buff), stdin); write(pipefd[1], buff, strlen(buff)+1); if(0 == strcmp(buff, "quit\n")) { break; } } wait(NULL); close(pipefd[1]); } else if(0 == pid) { close(pipefd[1]); while(1) { char buff[1024] = {0}; read(pipefd[0], buff, sizeof(buff)); if(0 == strcmp(buff, "quit\n")) { break; } printf("your write:%s", buff); } close(pipefd[0]); } else { perror("fail to fork\n"); return -1; } return 0; }
以上代码就是在父子进程中使用了pipe管道进行父子进程间的通信,父进程终端输入内容,在子进程中可以打印出来并且quit退出,以上要注意pipefd[0]和pipefd[1]端口的读写顺序,pipefd类似于文件描述符,要用文件IOwrite和read进行读写,用后记得关闭管道pipefd,避免浪费资源
边栏推荐
- J9 Digital Theory: DAO governance is more like an ecological process: governance is native to the network and continues to evolve
- Exception: try catch finally throws throw
- Elastic scaling of construction resources
- Use mysql statement to operate data table (table)
- HW-常见攻击方式和漏洞原理(2)
- Sigma development pays attention to details
- ArcGIS Pro 创建tpk
- ③ 关系数据库标准语言SQL 数据查询(SELECT)
- Linux install redis database
- Shell编程三剑客之sed
猜你喜欢
Linux安装redis数据库
使用mysql语句操作数据表(table)
QT+VTK+PCL拟合圆柱并计算起始点、中止点
Exceptions and exception handling mechanisms
ABP中的数据过滤器
C# using timer
sed of the Three Musketeers of Shell Programming
Pico 4更多参数曝光:Pancake+彩色透视,还有Pro版本
Two-dimensional array combat project -------- "Minesweeper Game"
C # - delegate detailed usage
随机推荐
The concept of services
php 判断数组是否为多维数组
MSTP——多生成树(案列+配置)
Sigma开发注意细节
什么是数组
深度解析:什么是太爱速M抢单模式?
BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection 论文笔记
版本号大小的判断方法
2022年PMP报考指南
微信小程序通过URL Scheme动态的渲染数据
容器技术真的是环境管理的救星吗?
Ambari Migrates Spark2 to Other Machines (Graphic and Text Tutorial)
什么是“门”电路(电子硬件)
Kunpeng compilation and debugging and basic knowledge of native development tools
Is container technology really the savior of environmental management?
#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 008-数据类型之整型
力扣------值相等的最小索引
小程序onPageNotFound的坑
二维数组实战项目--------《扫雷游戏》
Successfully resolved raise TypeError('Unexpected feature_names type')TypeError: Unexpected feature_names type