当前位置:网站首页>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);}
边栏推荐
猜你喜欢
随机推荐
抛出一个问题? Mysql环境下进行Count操作执行的时候速度很慢_需手动给主键添加索引---MySql优化001
程序员的专属浪漫——用3D Engine 5分钟实现烟花绽放效果
【原创】解决阿里云oss-browser.exe双击没反应打不开,提供一种解决方案
[项目配置] 配置Qt函数库和ui界面库的封装并调用的项目
Probably 95% of the people are still making PyTorch mistakes
分类预测 | MATLAB实现CNN-GRU(卷积门控循环单元)多特征分类预测
技术分享 | 如何模拟真实使用场景?mock 技术来帮你
判断一段文字的width
京东物流与五菱将开发联名版定制产品
面试官:MySQL 中 update 更新,数据与原数据相同时会执行吗?大部分人答不上来!
TELNET协议相关RFC
好久没更新博客了
markdown转ipynb--利用包notedown
BERT预训练模型(Bidirectional Encoder Representations from Transformers)-原理详解
【size_t是无符号整数 (-1 > 10) -> 1】
unix环境编程 第十五章 15.3 函数popen和pclose
By asking where the variables are stored, the shepherd boy laughed and said to use pointers, Go lang1.18 introductory refining tutorial, from Bai Ding to Hongru, the use of go lang type pointers (Poin
libavcodec.dll导致游戏不能运行及explorer关闭
antd表单
用Word写代码