linux无名管道
2024-09-27 01:42:28
特点
无名管道是半双工的,也就是说,一个管道要么只能读,要么只能写
只能在有共同祖先的进程间使用(父子进程、兄弟进程、子孙进程等)
fork或者execve调用创建的子进程,继承了父进程的文件描述符
通过man 2 pipe查看
#include <unistd.h>
int pipe(int pipefd[2]);
打开两个文件描述符,保存在pipefd中,其中pipefd[0]为读端,pipefd[1]为写端
无名管道写入操作不具有原子性,管道缓冲区一有空闲区域,写进程就会试图向管道写入数据。
不能使用lseek来定位
如果函数出错,返回值为-1,并设置errno
关闭管道用close函数
如果只有写管道,没有读管道,内核会发送SIFPIPE信号
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h> int main()
{
int pipefd[2] = {0}; if (-1 == pipe(pipefd))
{
fprintf(stderr, "pipe: %d, %s\n", errno, strerror(errno));
exit(1);
} pid_t pid = fork(); if (pid < 0)
{
fprintf(stderr, "fork: %d, %s\n", errno, strerror(errno));
exit(1);
}
if (pid > 0)
{
close(pipefd[0]);
char buf[] = "data from parent programe.";
write(pipefd[1], buf, strlen(buf));
close(pipefd[1]);
}
else
{
close(pipefd[1]);
char buf[60] = {0};
int readlen = read(pipefd[0], buf, 60);
printf("child read length: %d, %s\n", readlen, buf);
close(pipefd[0]);
wait(NULL);
} return 0;
}
管道局限性
- 只支持单向数据流
- 只能用于亲缘进程之间
- 没有名字
- 缓冲区有限(管道存在于内存中,创建管道时,分配缓冲区)
- 管道所传送的是无格式字节流,这就要求管道的读出方和写入方必须事先约定好数据的格式,比如多少字节算作一个消息(或命令、或记录)等等;
最新文章
- JavaScript toLocaleString() 方法
- [Leetcode][JAVA] Binary Tree Level Order Traversal
- js实现移动端手指左右上下滑动翻页效果
- iOS,iPhone各机型设备号,屏幕宽高,屏幕模式
- ubuntu16.04下opencv安装笔记和例程
- Unity3D模型的细致纹理问题解决办法
- SQL 查询45题
- 利用脚本设置本机IP地址
- 基础学习总结(六)--getContentRolver()的应用、内容监听者ContentObserver
- Eclipse下如何导入jar包
- MVC Filter自定义异常(拦截)
- Monkey Test
- python之6-3嵌套函数
- SQL优化 总结 精简
- JSP处理AJAX
- 用原生实现点击删除点击的li
- float是什么样式?
- # 2019-2020-3 《Java 程序设计》第五周学习总结
- java 判断两个时间段是否有交集
- 「loj3057」「hnoi2019」校园旅行
热门文章
- spring boot Configuration Annotation Proessor not found in classpath
- Design Pattern ->;Factory Method
- DXperience Winforms新版本13.2功能预览
- Android无需权限显示悬浮窗
- Struts1.x 基本原理及注册模块的实现
- 最近项目需要用到AdminLTE,所以整理一份中文版的小教程
- linux下搭建svn并同步更新至web目录
- 使用命令创建jenkins的job,解决jenkinsapi.custom_exceptions.JenkinsAPIException错误
- POJ-2718 Smallest Difference---DFS
- Nginx+Tomcat+memcached高可用会话保持