linux中使用匿名管道实现进程间通信
来源:互联网 发布:linux 固定ip 编辑:程序博客网 时间:2024/05/21 01:42
管道是最基本的IPC机制,由pipe函数创建。在调用pipe函数时,会在内存中创建一个缓冲区,称为管道。这个管道有两个端,一个读端和一个写端。通过filedes参数传给用户程序的两个文件描述符,filedes[0]指向管道的读端,filedes[1]指向管道的写端。
在linux中一切皆文件,管道可以看成是一个文件,可以通过read和write函数对管道进行读写操作。进程间通信时如何通过匿名管道实现的呢?
1.父进程调用pipe开辟管道,得到两个文件描述符指向管道的两端;
2.父进程调用fork创建子进程,子进程也有两个文件描述符指向管道的两端;
3.父进程关闭管道读端,子进程关闭管道写端,父进程可以往管道里写,子进程可以从管道里读。管道用环形队列实现,数据从写入端流入,读端流出,这样就实现了进程间通信。
#include<stdio.h>#include<unistd.h>#include<errno.h>#include<string.h>#include<sys/wait.h>int main(){<span style="white-space:pre"></span>int _pipe[2];int ret = pipe(_pipe);if(ret == -1){printf("creare pipe error\n");return 1;}pid_t id = fork();if(id < 0){printf("fork error\n");return 2;}else if(id == 0){close(_pipe[0]);int i = 0;char* mesg_c = NULL;while(i++ < 10){mesg_c = "i am a child!";write(_pipe[1],mesg_c,strlen(mesg_c)+1);sleep(1);}close(_pipe[1]);}else{close(_pipe[1]);char _mesg[100];int j = 0;while(j++ < 100){memset(_mesg,'\0',sizeof(_mesg));int ret = read(_pipe[0],_mesg,sizeof(_mesg));printf("%s:code is :%d\n",_mesg,ret);}if(waitpid(id,NULL,0) < 0)return 3;}return 0;}运行结果:
总结:进程通过文件描述符对管道进行控制,只有有血缘关系的进程才可以通过管道进行通信。
0 0
- linux中使用匿名管道实现进程间通信
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- android linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- Linux进程间通信——使用匿名管道
- linux进程间通信----之使用匿名管道
- Linux进程间通信——使用匿名管道
- caffe error
- 关于网上小卖部的设计和实现(一)
- Lua游戏开发—怪物,人物排序
- 读 T.N.F. 记录
- python小练1
- linux中使用匿名管道实现进程间通信
- linux epoll介绍
- 渲染路径-Deferred Lighting 延时光照
- Vertex Lit 顶点光照
- 正则表达式收集
- Forward Rendering 正向渲染
- QQ邮箱发送邮件代码及分析
- 【NOIP2016提高A组模拟8.19】(雅礼联考day2)总结
- GeometryService方法研究之relation