进程间通信--无名管道(pipe)
来源:互联网 发布:mc96f6432编程手册 编辑:程序博客网 时间:2024/05/20 15:37
无名管道通信(pipe)
无名管道通信主要用于父子进程之间,依赖fork的复制,或者vfork的共享,得以分享所得的无名管道的文件描述符。
总结其性质有以下几点
1. 管道是半双工的,数据在一个时间只能向一个方向流动;
2. 需要双方通信时,习惯于建立起两个管道(关闭一个的读端和另一个的写端)
3. 只能用于父子进程或者兄弟进程之间(具有亲缘关系的进程);
4. 通信过程发生在内核中,不依赖于文件系统(文件系统中不存在临时文件)
5. 写一次只能读一次
函数原型:
#include <unistd.h>int pipe(int pipefd[2]);
调用前int my_pipe[2] 这个用于存放当前管道的fd
my_pipe[0]为读端 my_pipe[1]为写端
所以在父子进程中要关闭其中的一端,
如父进程向子进程 那么父进程关闭读端,子进程关闭写端。
demo:
#include <unistd.h>#include <stdio.h>#include <errno.h>#include <string.h>#define BUF_SIZE 64int main(int argc, char const *argv[]){ int fd_pipe[2]; int ret = -1; const char word[] = {"hello world"}; char buf[64]; memset(buf, 0, sizeof(buf)); pipe(fd_pipe); ret = fork(); if(ret < 0){ perror("pipe"); return -1; } if(0 == ret){ printf("%s\n", "in parent process"); close(fd_pipe[0]); write(fd_pipe[1], word, sizeof(word)); }else{ printf("%s\n", "in child process"); sleep(1); read(fd_pipe[0], buf, BUF_SIZE); printf("I get :%s\n", buf); close(fd_pipe[1]); } return 0;}//Copyright (c) 2016 Copyright Holder All Rights Reserved.
0 0
- 进程间通信--无名管道(pipe)
- 1、进程间通信-PIPE(无名管道)
- 【Linux系统编程】进程间通信--无名管道(pipe)
- 进程通信-无名管道PIPE
- Linux进程间通信(一)之无名管道(PIPE)和有名管道(FIFO)
- 进程间通信IPC之--无名管道(pipe)和有名管道(fifo)
- 【六】 进程间通信——(PIPE)无名管道
- 进程间通信——(PIPE)无名管道
- Linux进程间通信之无名管道(PIPE)
- Linux编程 进程间通信------无名管道(PIPE)
- linux编程---进程间通信---PIPE---无名管道
- pipe无名管道通信
- 进程间通信(一)无名管道
- 进程间通信(2)-无名管道
- 进程间通信-管道(有名管道和无名管道)
- 进程间通信:无名管道
- 进程间通信--无名管道
- 进程间通信--无名管道
- BZOJ 1008 越狱 【数论】
- firewalld禁止被PING(丢弃ICMP包)
- mysql安装方法
- 只是展示一下
- 【C++】指针(3):指针&数组
- 进程间通信--无名管道(pipe)
- 解决drupal下使用composer时报错:Failed to decode response: zlib_decode(): data error
- DTW动态规划调整
- 稳定排序
- windows下安装配置octave(仅供记录)
- 自己不优秀,认识谁都没用
- 在ubuntu下pyenv管理python的多个版本
- Python学习笔记03_条件判断和循环
- 38-2-1