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

相关文章

Oracle数据库定时备份脚本方式(Linux)

《Oracle数据库定时备份脚本方式(Linux)》文章介绍Oracle数据库自动备份方案,包含主机备份传输与备机解压导入流程,强调需提前全量删除原库数据避免报错,并需配置无密传输、定时任务及验证脚本... 目录说明主机脚本备机上自动导库脚本整个自动备份oracle数据库的过程(建议全程用root用户)总结

Linux如何查看文件权限的命令

《Linux如何查看文件权限的命令》Linux中使用ls-R命令递归查看指定目录及子目录下所有文件和文件夹的权限信息,以列表形式展示权限位、所有者、组等详细内容... 目录linux China编程查看文件权限命令输出结果示例这里是查看tomcat文件夹总结Linux 查看文件权限命令ls -l 文件或文件夹

idea的终端(Terminal)cmd的命令换成linux的命令详解

《idea的终端(Terminal)cmd的命令换成linux的命令详解》本文介绍IDEA配置Git的步骤:安装Git、修改终端设置并重启IDEA,强调顺序,作为个人经验分享,希望提供参考并支持脚本之... 目录一编程、设置前二、前置条件三、android设置四、设置后总结一、php设置前二、前置条件

Linux系统中查询JDK安装目录的几种常用方法

《Linux系统中查询JDK安装目录的几种常用方法》:本文主要介绍Linux系统中查询JDK安装目录的几种常用方法,方法分别是通过update-alternatives、Java命令、环境变量及目... 目录方法 1:通过update-alternatives查询(推荐)方法 2:检查所有已安装的 JDK方

Linux系统之lvcreate命令使用解读

《Linux系统之lvcreate命令使用解读》lvcreate是LVM中创建逻辑卷的核心命令,支持线性、条带化、RAID、镜像、快照、瘦池和缓存池等多种类型,实现灵活存储资源管理,需注意空间分配、R... 目录lvcreate命令详解一、命令概述二、语法格式三、核心功能四、选项详解五、使用示例1. 创建逻

Linux下在线安装启动VNC教程

《Linux下在线安装启动VNC教程》本文指导在CentOS7上在线安装VNC,包含安装、配置密码、启动/停止、清理重启步骤及注意事项,强调需安装VNC桌面以避免黑屏,并解决端口冲突和目录权限问题... 目录描述安装VNC安装 VNC 桌面可能遇到的问题总结描js述linux中的VNC就类似于Window

linux下shell脚本启动jar包实现过程

《linux下shell脚本启动jar包实现过程》确保APP_NAME和LOG_FILE位于目录内,首次启动前需手动创建log文件夹,否则报错,此为个人经验,供参考,欢迎支持脚本之家... 目录linux下shell脚本启动jar包样例1样例2总结linux下shell脚本启动jar包样例1#!/bin

Linux之platform平台设备驱动详解

《Linux之platform平台设备驱动详解》Linux设备驱动模型中,Platform总线作为虚拟总线统一管理无物理总线依赖的嵌入式设备,通过platform_driver和platform_de... 目录platform驱动注册platform设备注册设备树Platform驱动和设备的关系总结在 l

linux批量替换文件内容的实现方式

《linux批量替换文件内容的实现方式》本文总结了Linux中批量替换文件内容的几种方法,包括使用sed替换文件夹内所有文件、单个文件内容及逐行字符串,强调使用反引号和绝对路径,并分享个人经验供参考... 目录一、linux批量替换文件内容 二、替换文件内所有匹配的字符串 三、替换每一行中全部str1为st

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处