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 join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

Linux云服务器手动配置DNS的方法步骤

《Linux云服务器手动配置DNS的方法步骤》在Linux云服务器上手动配置DNS(域名系统)是确保服务器能够正常解析域名的重要步骤,以下是详细的配置方法,包括系统文件的修改和常见问题的解决方案,需要... 目录1. 为什么需要手动配置 DNS?2. 手动配置 DNS 的方法方法 1:修改 /etc/res

Linux创建服务使用systemctl管理详解

《Linux创建服务使用systemctl管理详解》文章指导在Linux中创建systemd服务,设置文件权限为所有者读写、其他只读,重新加载配置,启动服务并检查状态,确保服务正常运行,关键步骤包括权... 目录创建服务 /usr/lib/systemd/system/设置服务文件权限:所有者读写js,其他

Linux下利用select实现串口数据读取过程

《Linux下利用select实现串口数据读取过程》文章介绍Linux中使用select、poll或epoll实现串口数据读取,通过I/O多路复用机制在数据到达时触发读取,避免持续轮询,示例代码展示设... 目录示例代码(使用select实现)代码解释总结在 linux 系统里,我们可以借助 select、

Linux挂载linux/Windows共享目录实现方式

《Linux挂载linux/Windows共享目录实现方式》:本文主要介绍Linux挂载linux/Windows共享目录实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录文件共享协议linux环境作为服务端(NFS)在服务器端安装 NFS创建要共享的目录修改 NFS 配

linux系统中java的cacerts的优先级详解

《linux系统中java的cacerts的优先级详解》文章讲解了Java信任库(cacerts)的优先级与管理方式,指出JDK自带的cacerts默认优先级更高,系统级cacerts需手动同步或显式... 目录Java 默认使用哪个?如何检查当前使用的信任库?简要了解Java的信任库总结了解 Java 信

Linux命令rm如何删除名字以“-”开头的文件

《Linux命令rm如何删除名字以“-”开头的文件》Linux中,命令的解析机制非常灵活,它会根据命令的开头字符来判断是否需要执行命令选项,对于文件操作命令(如rm、ls等),系统默认会将命令开头的某... 目录先搞懂:为啥“-”开头的文件删不掉?两种超简单的删除方法(小白也能学会)方法1:用“--”分隔命