温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Linux中有名管道是什么意思

发布时间:2021-10-27 11:35:31 来源:亿速云 阅读:184 作者:小新 栏目:系统运维

这篇文章主要介绍Linux中有名管道是什么意思,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

一、管道的概念

管道,又名「无名管理」,或「匿名管道」,管道是一种非常基本,也是使用非常频繁的IPC方式。

Linux中有名管道是什么意思

1. 管道本质

  • 管道的本质也是一种文件,不过是伪文件,实际上是一块内核缓冲区,大小4K;

  • 管道创建以后会产生两个文件描述符,一个是读端,另一个是写端;

  • 管道里的数据只能从写端被写入,从读端被读出;

1. 管道原理

管道是内核的一块缓冲区,更具体一些,是一个环形队列。数据从队列的一端写入数据,另一端读出,如下图示:

Linux中有名管道是什么意思

3. 管道的优点

简单

4.  管道的缺点

  • 只能单向通信,如果需要双向通信则需要建立两个管道;

  • 只能应用于具有血缘关系的进程,如父子进程;

  • 缓冲区大小受限,通常为1页,即4k;

二、管道的创建

管道创建三步曲:

  • 父进程调用pipe函数创建管道;

  • 父进程调用fork函数创建子进程;

  • 父进程关闭fd[0],子进程关闭fd[1];

具体如下图所示:

Linux中有名管道是什么意思

三、管道的读写行为

  • 管道的缓冲区大小固定为4k,所以如果管道内数据已经写满,则无法再写入数据,进程的write调用将阻塞,直到有足够的空间再写入数据;

  • 管道的读动作比写动作要快,数据一旦被读走了,管道将释放相应的空间,以便后续数据的写入。当所有的数据都读完之后,进程的read()调用将阻塞,直到有数据再次写入。

四、例程

父子间通信:

#include <stdio.h>  #include <sys/types.h>  #include <unistd.h>  #include <string.h>    int main()  {      int fd[2];      pid_t pid;     char buf[1024];     char *data = "hello world!";      /* 创建管道 */     if (pipe(fd) == -1) {         printf("ERROR: pipe create failed!\n");         return -1;     }      pid = fork();     if (pid == 0) {         /* 子进程 */         close(fd[1]);   // 子进程读取数据,关闭写端         read(fd[0], buf, sizeof(buf));  // 从管道读数据         printf("child process read: %s\n", buf);         close(fd[0]);     } else if (pid > 0) {         /* 父进程 */         close(fd[0]);   //父进程写数据,关闭读端         write(fd[1], data, strlen(data));   // 向管道写数据         printf("parent process write: %s\n", data);         close(fd[1]);     }      return 0; }

兄弟间通信:

 #include <stdio.h>  #include <sys/types.h>  #include <unistd.h>  #include <string.h>  #include <sys/wait.h>    int main ()  {      int fd[2];     int i = 0;     pid_t pid;     char buf[1024];     char *data = "hello world!";      /* 创建管道 */     if (pipe(fd) == -1) {         printf("ERROR: pipe create failed!\n");         return -1;     }      for (i = 0; i < 2; i++) {         pid = fork();         if (pid == -1) {             printf("ERROR: fork error!\n");             return -1;         } else if (pid == 0) {             break;         }     }      /* 通过i来判断创建的子进程及父进程 */     if (i == 0) {         /* 第一个子进程,兄进程 */         close(fd[0]);   // 兄进程向弟进程写数据,关闭读端         write(fd[1], data, strlen(data));         printf("elder brother send: %s\n", data);         close(fd[1]);     } else if (i == 1) {         /* 第二个子进程,弟进程 */         close(fd[1]);         read(fd[0], buf, sizeof(buf));         printf("younger brother receive: %s\n", buf);         close(fd[0]);     } else {         /* 父进程 */         close(fd[0]);         close(fd[1]);         for (i = 0; i < 2; i++) {             wait(NULL);         }     }      return 0; }

以上是“Linux中有名管道是什么意思”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI