当前位置:网站首页>Unix System Programming Chapter 15 15.2 Pipes
Unix System Programming Chapter 15 15.2 Pipes
2022-08-09 10:28:00 【Mary soda Patty】
Pipe is the oldest form of IPC in UNIX systems, and all UNIX systems provide this communication mechanism.
Pipelines have two limitations:
- Historically, they were half-duplex (ie data only flowed in one direction).Some systems now offer full-duplex pipes.
- Pipes can only be used between two processes with a common ancestor. Usually, a pipe is created by a process. After the process calls fork, the pipe can be used between the parent process and the child process.
We will see that FIFOs do not have the second limitation, and UNIX domain sockets do not have either.
A pipe is created by calling the pipe function.
#include int pipe(int fd[2]);//Return value, return 0 for success, -1 for error
Two file descriptors are returned via the parameter fd: fd[0] is open for reading and fd[1] is open for writing.The output of fd[1] is the input of fd[0].
A pipe for a single process is of little use, usually a process will call pipe followed by fork to create an IPC channel from parent to child and vice versa.
What to do after the fork depends on the direction of data flow we want. For pipes from parent to child, the parent closes the read end of the pipe and the child closes the write end.
The following two rules apply when one end of the pipe is closed.
- When reading a pipe whose write end has been closed, after all data has been read, read returns 0, indicating end of file.
- If writing to a channel whose read end has been closed, the signal SIGPIPE is generated. If the signal is ignored or caught and returned from its handler, write returns -1 and errno is set to EPIPE.
Sample program:
#include "apue.h"int main(){int n;int fd[2];pid_t pid;char line[MAXLINE];if(pipe(fd)<0)err_sys("pipe error");if((pid=fork())<0)err_sys("fork error");else if(pid>0){close(fd[0]);write(fd[1],"hello world\n",12);}else{close(fd[1]);n=read(fd[0],line,MAXLINE);write(STDOUT_FILENO,line,n);}exit(0);}
边栏推荐
猜你喜欢
随机推荐
Technology Sharing | Sending Requests Using cURL
面试官:MySQL 中 update 更新,数据与原数据相同时会执行吗?大部分人答不上来!
10000以内素数表(代码块)
unix环境编程 第十五章 15.10 POSIX信号量
The GNU Privacy Guard
UNIX Environment Programming Chapter 15 15.5FIFO
electron 应用开发优秀实践
主从postition变化无法锁定_Slave_IO_Running显示No_Slave_Sql_Running显示No---Mysql主从复制同步002
unix环境编程 第十五章 15.9 共享存储
1002 写出这个数 (20 分)
分类预测 | MATLAB实现CNN-LSTM(卷积长短期记忆神经网络)多特征分类预测
自启服务mock联调跨域问题
Apache Log4j 2 远程代码执行漏洞详解
Redis 缓存主动更新策略
Redis cache update strategy actively
OpenGL ES2.0编程三部曲(转载自MyArrow)
使用cpolar远程连接群晖NAS(创建临时链接)
单元测试2之实际结果检查的引用
Master-slave postition changes cannot be locked_Slave_IO_Running shows No_Slave_Sql_Running shows No---Mysql master-slave replication synchronization 002
编程技术提升