Linux系统编程- 无名管道(匿名管道)

2024-05-13 06:38

本文主要是介绍Linux系统编程- 无名管道(匿名管道),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

无名管道作为Linux进程间通讯,我们这里把理论和实际结合起来说明。

1.什么是管道

管道,英文位pipe,在学习linux系统编程一个重要概念.它的发明人是道格拉斯.麦克罗伊,这位也是UNIX上早期shell的发明人。他在发明了shell之后,发现系统操作执行命令的时候,经常有需求要将一个程序的输出交给另一个程序进行处理,这种操作可以使用输入输出重定向加文件搞定,比如:

输入以下命令行:

yates@yates-virtual-machine:~/test/code/FOLDER$ ls  -l /etc/ > etc.txt
yates@yates-virtual-machine:~/test/code/FOLDER$ wc -l etc.txt 
255 etc.txt

后面发明管道,在shell中,可以使用 “|”连接个命令,shell会把前后两个命令输入输出用一个管道相连,以便得到进程间通讯的目的。

yates@yates-virtual-machine:~/test/code/FOLDER$ ls  -l /etc/ | wc -l
255

以上两种方法,你认为分开两个进程,前面进程以写入方式打开文件,后面以读的方式打开。管道内容缓存在内存中。

无名管道:

它的特点只能在父子进程中使用,父进程产生子进程前打开一个管道文件,然后fork后,子进程拷贝父进程的管道文件描述符,以达到共用一个管道通信的目的。除了父子进程外,别的都不知道该管道文件符,确保数据传输安全性。

 

创建匿名管道:

匿名管道创建非常简单,用pipe函数创建出两个文件描述符,再用write,read分别对管道进行读写数据。请看以下demo

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define BUFSIZE 4096
#define STRING "1231313"int main(void)
{int fd[2];char buf[BUFSIZ];if (pipe(fd) == -1){perror("pipe error");exit(1);}int ret;int count = 0;ret = write(fd[1], STRING, strlen(STRING));if (ret < 0){perror("write error ");exit(1);}ret = read(fd[0],buf,sizeof(buf));if(ret < 0){perror("read error");exit(1);}printf("read buffer =%s\r\n",buf);exit(0);
}

以上代码执行结果是

yates@yates-virtual-machine:~/test/code/FOLDER$ ./pipe 
read buffer =1231313

以上demo列举最简单匿名管道创建和读写操作。

 

注意:fd[1]用来写操作,fd[0]用来读操作。

如果在两个进程之间,应该怎么通过管道进行通讯呢?

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>#include <fcntl.h>
#define BUFSIZE 4096
#define STRING "1231313"
int main()
{int pipefd[2];pid_t pid;char buf[BUFSIZ];if (pipe(pipefd) == -1){perror("pipe error\r\n");exit(1);}int ret = 0;pid = fork();if (pid == -1){perror("fork error \r\n");exit(1);}else if (pid == 0){printf("this is a child,pid=%d\r\n", getpid());write(pipefd[1], STRING, strlen(STRING));}else{printf("this is a father , pid=%d\r\n", getpid());ret = read(pipefd[0], buf, sizeof(STRING));if(ret<0){printf("read data error %d\r\n",ret);exit(1);}printf("%s\r\n", buf);}exit(0);
}

以上demo运行结果是:

yates@yates-virtual-machine:~/test/code/FOLDER$ ./pipe 
this is a father , pid=10043
this is a child,pid=10044
1231313

 

阻塞和非阻塞

管道可以分为阻塞和非阻塞,通过fcntl函数设置

当没有数据可读时

  • O_NONBLOCK disable:read调用阻塞,即进程暂停执行,一直等到有数据来到为止。
  • O_NONBLOCK enable:read调用返回-1,errno值为EAGAIN。

当管道满的时候

  • O_NONBLOCK disable: write调用阻塞,直到有进程读走数据
  • O_NONBLOCK enable:调用返回-1,errno值为EAGAIN

当默认创建文件描述符时,默认是打开阻塞模式,请看一下demo。

情况一:默认打开阻塞模式,只有读操作

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>#include <fcntl.h>
#define BUFSIZE 4096
#define STRING "1231313"int main(void)
{int fd[2];char buf[BUFSIZ];if (pipe(fd) == -1){perror("pipe error");exit(1);}int ret;int count = 0;printf("ready to read pipe data\r\n");ret = read(fd[0],buf,sizeof(buf));if (ret < 0){perror("read error ");exit(1);}printf("buffer:%s\r\n",buf);
}

运行以上demo结果是:

yates@yates-virtual-machine:~/test/code/FOLDER$ ./pipe 
ready to read pipe data

程序一直阻塞在read函数,因为此时read函数默认为阻塞模式。

情况二:非阻塞read

通过设置fcntl函数设置read模式为非阻塞模式。

 int flag = fcntl(fd[0],F_GETFL); //读取默认模式
 ret = fcntl(fd[0],F_SETFL,flag | O_NONBLOCK);//使能非阻塞模式

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>#include <fcntl.h>
#define BUFSIZE 4096
#define STRING "1231313"
int main(void)
{int fd[2];char buf[BUFSIZ];if (pipe(fd) == -1){perror("pipe error");exit(1);}int ret;int count = 0;int flag = fcntl(fd[0],F_GETFL);//读取默认配置ret = fcntl(fd[0],F_SETFL,flag | O_NONBLOCK);//使能非阻塞模式printf("ready to read pipe data\r\n");ret = read(fd[0],buf,sizeof(buf));if (ret < 0){printf("read error :%d\r\n",ret);exit(1);}printf("buffer:%s\r\n",buf);
}

执行以上程序结果是:

yates@yates-virtual-machine:~/test/code/FOLDER$ ./pipe 
ready to read pipe data
read error :-1

结论:当没有write函数情况下,raad函数立即返回为-1.

 

情景三:如果先关闭写文件描述符,在非阻塞模式下只读取数据

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>#include <fcntl.h>
#define BUFSIZE 4096
#define STRING "1231313"
int main(void)
{int fd[2];char buf[BUFSIZ];if (pipe(fd) == -1){perror("pipe error");exit(1);}int ret;int count = 0;int flag = fcntl(fd[0],F_GETFL);ret = fcntl(fd[0],F_SETFL,flag | O_NONBLOCK);printf("ready to read pipe data\r\n");close(fd[1]);ret = read(fd[0],buf,sizeof(buf));if (ret < 0){printf("read error :%d\r\n",ret);exit(1);}printf("ret=%d,buffer:%s\r\n",ret,buf);
}

执行以上demo结果是

yates@yates-virtual-machine:~/test/code/FOLDER$ ./pipe 
ready to read pipe data
ret=0,buffer:

当关闭写文件描述符时,read函数立马返回0.

会有小伙伴问,如果关闭读文件描述符fd[0]能,这里不上代码,read函数结果返回-1.

结论:在非阻塞模式下,当关闭写文件描述符时,read函数立马返回0。如果关闭读文件描述符fd[0]能,read结果返回-1。

 

情景四:如果在阻塞模式下,只写入数据。

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>#include <fcntl.h>
#define BUFSIZE 4096
#define STRING "1231313"
int main(void)
{int fd[2];if (pipe(fd) == -1){perror("pipe error");exit(1);}int ret;int count = 0;ret = write(fd[1], STRING, strlen(STRING));if (ret < 0){perror("write error ");exit(1);}printf("end\r\n");
}

运行结果是:

yates@yates-virtual-machine:~/test/code/FOLDER$ ./pipe 
end

说明第一次写入write成功,但是如果循环写入呢?

yates@yates-virtual-machine:~/test/code/FOLDER$ ./pipe 
write count=0
write count=1
write count=2
write count=3
write count=4
write count=5
write count=6
write count=7
write count=8
write count=9
write count=10
...
write count=9352
write count=9353
write count=9354
write count=9355
write count=9356
write count=9357
write count=9358
write count=9359

结果去到9359次停止,为什么呢?

这里需要说到管道容量。

管道实际上就是内核控制的一个内存缓冲区,有容量上线,我们这里把最大缓冲大小命名为PIPESIZE,注意,PIPESIZE最小为一页,如果电脑磁盘格式为4k的话,那PIPESIZE最小为4096,但是在64位ubuntu系统上,通过查看/proc/sys/fs/pipe-max-size ,PIPESIZE设置为1048576(2^20)。

管道容量大小可以设置的,通过fcntl 设置F_SETPIPE_SZ设置容量大小,注意最低为1page(一般系统为4096)。

int ret = fcntl(fd[1],F_SETPIPE_SZ,BUFSIZE);//该函数设置管道大小。

请看以下demo

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>#include <fcntl.h>
#define BUFSIZE 4096
#define STRING "1231313"
int main(void){int fd[2];if(pipe(fd)==-1){perror("pipe error");exit(1);}int ret ;int count =0;ret = fcntl(fd[1],F_SETPIPE_SZ,BUFSIZE);while(1){ret = write(fd[1],STRING,strlen(STRING));if(ret < 0 ){perror("write error ");exit(1);}printf("write count=%d\r\n",count);count ++;}
}

以上demo执行结果为

yates@yates-virtual-machine:~/test/code/FOLDER$ ./pipe 
write count=0
write count=1
write count=2
write count=3
write count=4
write count=5
write count=6
write count=7
write count=8
write count=9
write count=10
write count=11
write count=12
write count=13
write count=14
write count=15
write count=16
write count=17
write count=18
write count=19
write count=20
write count=21
write count=22
write count=23
write count=24
write count=25
...
write count=567
write count=568
write count=569
write count=570
write count=571
write count=572
write count=573
write count=574
write count=575
write count=576
write count=577
write count=578
write count=579
write count=580
write count=581
write count=582
write count=583
write count=584

比上个demo代码write执行次数少了很多。

结论:在阻塞模式下,当管道容量未达到上上限时,write函数可以成功写进入,当达到容量上限是,write函数会一直阻塞。

 

场景五:在非阻塞模式下一直写入

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>#include <fcntl.h>
#define BUFSIZE 4096
#define STRING "1231313"
int main(void){int fd[2];if(pipe(fd)==-1){perror("pipe error");exit(1);}int ret ;int count =0;int flag = fcntl(fd[1],F_GETFL);fcntl(fd[1],F_SETFL,flag|O_NONBLOCK);ret = fcntl(fd[1],F_SETPIPE_SZ,BUFSIZE);while(1){ret = write(fd[1],STRING,strlen(STRING));if(ret < 0 ){perror("write error ");exit(1);}printf("write count=%d\r\n",count);count ++;}
}

运行结果为

yates@yates-virtual-machine:~/test/code/FOLDER$ ./pipe 
write count=0
write count=1
write count=2
write count=3
write count=4
write count=5
write count=6
write count=7
write count=8
write count=9
write count=10...
write count=560
write count=561
write count=562
write count=563
write count=564
write count=565
write count=566
write count=567
write count=568
write count=569
write count=570
write count=571
write count=572
write count=573
write count=574
write count=575
write count=576
write count=577
write count=578
write count=579
write count=580
write count=581
write count=582
write count=583
write count=584
write error : Resource temporarily unavailable

结论,当PIPESIZE满的时候,write函数返回为-1.

按照以上场景,总结出以下结论:

O_NONBLOCK关闭,n <= PIPESIZE

n个字节的写入操作是原子操作,write系统调用可能会因为管道容量(PIPESIZE)没有足够的空间存放n字节长度而阻塞。

O_NONBLOCK打开,n <= PIPESIZE

如果有足够的空间存放n字节长度,write调用会立即返回成功,并且对数据进行写操作。空间不够则立即报错返回,并且errno被设置为EAGAIN。

O_NONBLOCK关闭,n > PIPESIZE

对n字节的写入操作不保证是原子的,就是说这次写入操作的数据可能会跟其他进程写这个管道的数据进行交叉。当管道容量长度低于要写的数据长度的时候write操作会被阻塞。

O_NONBLOCK打开,n > PIPESIZE

如果管道空间已满。write调用报错返回并且errno被设置为EAGAIN。如果没满,则可能会写入从1到n个字节长度,这取决于当前管道的剩余空间长度,并且这些数据可能跟别的进程的数据有交叉。

这篇关于Linux系统编程- 无名管道(匿名管道)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/984950

相关文章

Linux ls命令操作详解

《Linuxls命令操作详解》通过ls命令,我们可以查看指定目录下的文件和子目录,并结合不同的选项获取详细的文件信息,如权限、大小、修改时间等,:本文主要介绍Linuxls命令详解,需要的朋友可... 目录1. 命令简介2. 命令的基本语法和用法2.1 语法格式2.2 使用示例2.2.1 列出当前目录下的文

利用Python快速搭建Markdown笔记发布系统

《利用Python快速搭建Markdown笔记发布系统》这篇文章主要为大家详细介绍了使用Python生态的成熟工具,在30分钟内搭建一个支持Markdown渲染、分类标签、全文搜索的私有化知识发布系统... 目录引言:为什么要自建知识博客一、技术选型:极简主义开发栈二、系统架构设计三、核心代码实现(分步解析

Linux中的计划任务(crontab)使用方式

《Linux中的计划任务(crontab)使用方式》:本文主要介绍Linux中的计划任务(crontab)使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、前言1、linux的起源与发展2、什么是计划任务(crontab)二、crontab基础1、cro

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

Linux系统配置NAT网络模式的详细步骤(附图文)

《Linux系统配置NAT网络模式的详细步骤(附图文)》本文详细指导如何在VMware环境下配置NAT网络模式,包括设置主机和虚拟机的IP地址、网关,以及针对Linux和Windows系统的具体步骤,... 目录一、配置NAT网络模式二、设置虚拟机交换机网关2.1 打开虚拟机2.2 管理员授权2.3 设置子

揭秘Python Socket网络编程的7种硬核用法

《揭秘PythonSocket网络编程的7种硬核用法》Socket不仅能做聊天室,还能干一大堆硬核操作,这篇文章就带大家看看Python网络编程的7种超实用玩法,感兴趣的小伙伴可以跟随小编一起... 目录1.端口扫描器:探测开放端口2.简易 HTTP 服务器:10 秒搭个网页3.局域网游戏:多人联机对战4.

Linux系统中卸载与安装JDK的详细教程

《Linux系统中卸载与安装JDK的详细教程》本文详细介绍了如何在Linux系统中通过Xshell和Xftp工具连接与传输文件,然后进行JDK的安装与卸载,安装步骤包括连接Linux、传输JDK安装包... 目录1、卸载1.1 linux删除自带的JDK1.2 Linux上卸载自己安装的JDK2、安装2.1

Java并发编程必备之Synchronized关键字深入解析

《Java并发编程必备之Synchronized关键字深入解析》本文我们深入探索了Java中的Synchronized关键字,包括其互斥性和可重入性的特性,文章详细介绍了Synchronized的三种... 目录一、前言二、Synchronized关键字2.1 Synchronized的特性1. 互斥2.

Linux卸载自带jdk并安装新jdk版本的图文教程

《Linux卸载自带jdk并安装新jdk版本的图文教程》在Linux系统中,有时需要卸载预装的OpenJDK并安装特定版本的JDK,例如JDK1.8,所以本文给大家详细介绍了Linux卸载自带jdk并... 目录Ⅰ、卸载自带jdkⅡ、安装新版jdkⅠ、卸载自带jdk1、输入命令查看旧jdkrpm -qa