Linux中有名管道是什么意思

发布时间:2021-10-27 11:35:31 作者:小新
来源:亿速云 阅读:187

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

一、管道的概念

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

Linux中有名管道是什么意思

1. 管道本质

1. 管道原理

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

Linux中有名管道是什么意思

3. 管道的优点

简单

4.  管道的缺点

二、管道的创建

管道创建三步曲:

具体如下图所示:

Linux中有名管道是什么意思

三、管道的读写行为

四、例程

父子间通信:

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

推荐阅读:
  1. linux中的编译是什么意思
  2. linux中的was是什么意思

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

linux

上一篇:有哪些提高代码性能的编程小技巧

下一篇:在java中如何编写规范的代码

相关阅读

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

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