当前位置:网站首页>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);}边栏推荐
猜你喜欢
随机推荐
1002 写出这个数 (20 分)
xmms的均衡器试验成功 音效相当不错 比rockbox可能还要好
BERT预训练模型(Bidirectional Encoder Representations from Transformers)-原理详解
The common problems in laptops, continuously updated
今天做了手机播放器的均衡器
常用语言图表库总结
浅析JWT安全问题
1001 害死人不偿命的(3n+1)猜想 (15 分)
snmp++编译错误问题解决方法
虚拟列表key复用问题
RTP
antd的Table列选择、列拓展
MySQL索引的B+树到底有多高?
强化学习 (Reinforcement Learning)
Win7 远程桌面限制IP
day16_03集合
stimulus.js 初体验
Unix Environment Programming Chapter 15 15.9 Shared Storage
京东物流与五菱将开发联名版定制产品
10000以内素数表(代码块)









