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的ffmpeg python的关键帧抽取

《基于Linux的ffmpegpython的关键帧抽取》本文主要介绍了基于Linux的ffmpegpython的关键帧抽取,实现以按帧或时间间隔抽取关键帧,文中通过示例代码介绍的非常详细,对大家的学... 目录1.FFmpeg的环境配置1) 创建一个虚拟环境envjavascript2) ffmpeg-py

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

Linux链表操作方式

《Linux链表操作方式》:本文主要介绍Linux链表操作方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、链表基础概念与内核链表优势二、内核链表结构与宏解析三、内核链表的优点四、用户态链表示例五、双向循环链表在内核中的实现优势六、典型应用场景七、调试技巧与

基于Python实现一个简单的题库与在线考试系统

《基于Python实现一个简单的题库与在线考试系统》在当今信息化教育时代,在线学习与考试系统已成为教育技术领域的重要组成部分,本文就来介绍一下如何使用Python和PyQt5框架开发一个名为白泽题库系... 目录概述功能特点界面展示系统架构设计类结构图Excel题库填写格式模板题库题目填写格式表核心数据结构

详解Linux中常见环境变量的特点与设置

《详解Linux中常见环境变量的特点与设置》环境变量是操作系统和用户设置的一些动态键值对,为运行的程序提供配置信息,理解环境变量对于系统管理、软件开发都很重要,下面小编就为大家详细介绍一下吧... 目录前言一、环境变量的概念二、常见的环境变量三、环境变量特点及其相关指令3.1 环境变量的全局性3.2、环境变

Linux系统中的firewall-offline-cmd详解(收藏版)

《Linux系统中的firewall-offline-cmd详解(收藏版)》firewall-offline-cmd是firewalld的一个命令行工具,专门设计用于在没有运行firewalld服务的... 目录主要用途基本语法选项1. 状态管理2. 区域管理3. 服务管理4. 端口管理5. ICMP 阻断

Linux实现线程同步的多种方式汇总

《Linux实现线程同步的多种方式汇总》本文详细介绍了Linux下线程同步的多种方法,包括互斥锁、自旋锁、信号量以及它们的使用示例,通过这些同步机制,可以解决线程安全问题,防止资源竞争导致的错误,示例... 目录什么是线程同步?一、互斥锁(单人洗手间规则)适用场景:特点:二、条件变量(咖啡厅取餐系统)工作流

Linux中修改Apache HTTP Server(httpd)默认端口的完整指南

《Linux中修改ApacheHTTPServer(httpd)默认端口的完整指南》ApacheHTTPServer(简称httpd)是Linux系统中最常用的Web服务器之一,本文将详细介绍如何... 目录一、修改 httpd 默认端口的步骤1. 查找 httpd 配置文件路径2. 编辑配置文件3. 保存

Linux使用scp进行远程目录文件复制的详细步骤和示例

《Linux使用scp进行远程目录文件复制的详细步骤和示例》在Linux系统中,scp(安全复制协议)是一个使用SSH(安全外壳协议)进行文件和目录安全传输的命令,它允许在远程主机之间复制文件和目录,... 目录1. 什么是scp?2. 语法3. 示例示例 1: 复制本地目录到远程主机示例 2: 复制远程主

Windows 系统下 Nginx 的配置步骤详解

《Windows系统下Nginx的配置步骤详解》Nginx是一款功能强大的软件,在互联网领域有广泛应用,简单来说,它就像一个聪明的交通指挥员,能让网站运行得更高效、更稳定,:本文主要介绍W... 目录一、为什么要用 Nginx二、Windows 系统下 Nginx 的配置步骤1. 下载 Nginx2. 解压