当前位置:首页 > 操作系统 > Linux

Linux中的管道


1.管道是进程间通信的一种重要手段,在linux中没有使用 专门 的数据结构,而是借助了文件系统的file结构和VFS索引节点inode。通过两个file结构指向同一个临时的VFS索引节点,而这个索引节点又指向一个物理页面实现的。如下图所示:


技术分享650) this.width=650;" src="/upload/getfiles/default/2022/11/10/20221110051853623.jpg" title="捕获.PNG" />


管道的实现的源代码在fs/pipe.c中,其中pipe_read()和pipe_write()是管道的读写函数。管道写函数通过将字节复制到 VFS 索引节点指向的物理内存而写入数据,而管道读函数则通过复制物理内存中的字节而读出数据。当然,内核必须利用一定的机制同步对管道的访问,为此,内核使用了锁、等待队列和信号。

2.匿名管道(pipe)

   常用于父子进程,也用于有血缘关系的进程间的通信。  举例:父进程与子进程之间的通信。

  技术分享650) this.width=650;" src="/upload/getfiles/default/2022/11/10/20221110051853898.jpg" title="pipe.png" />

因为匿名管道提供的进程通信是单向的,所以去掉上图中子的读(写),去掉父的写(读)。就可以实现子写父读(子读父写)。

代码实现子写父读:

  
  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<unistd.h>
  4 #include<string.h>
  5 #include<sys/types.h>
  6
  7 int main()
  8 {
  9   //1.创建管道
 10   int pipe_fd[2]={-1,-1};
 11   if(pipe(pipe_fd)<0)
 12   {
 13     perror("pipe");
 14     exit(1);
 15 
 16    }
 17  // printf("0-> %d,1-> %d",pipe_fd[0],pipe_fd[1]);检查读写
 18  //2.创建进程
 19  pid_t pid=fork();
 20  if(pid<0)
 21   {
 22     perror("fork");
 23     exit(2);
 24 
 25   }
 26 else if(pid==0)
 27 {
 28   //子进程
 29   close(pipe_fd[0]);
 30   int count=10;
 31   char buf[]="hello bit";
 32   while(count)
 33    {
 34       write(pipe_fd[1],buf, strlen(buf));
 35       count--;
 36       sleep(1);
 37    }
 38   close(pipe_fd[1]);
 39  }
 40 else
 41   {
        //父进程
 42     close(pipe_fd[1]);
 43     char buf[1024];
 44     while(1)
 45     {
 46       memset(buf,‘‘,sizeof(buf)-1);
 47       ssize_t size=read(pipe_fd[0],buf,sizeof(buf)-1);
 48       if(size>0)
 49        {
 50          buf[size]=‘‘;
 51          printf("%sn",buf);
 52 
 53         }
 54      }
 55     }
 56    close(pipe_fd[0]);
 57    return 0;
 58  }             
                                                                1,7           Top

程序执行结果:

技术分享650) this.width=650;" src="/upload/getfiles/default/2022/11/10/20221110051854145.jpg" title=")1T@DLD9JG{LI8YAP7UJ]{E.png" />

父进程读取到子写的10条信息。

匿名管道的特点总结:

1.进程之间的通信是单向的

2.用于父子进程和有血缘关系的进程

3.提供的是流式服务

4.管道内部处理了数据写齐备然后才能读的机制

5.生命周期随进程。



本文出自 “输出菱形图案” 博客,请务必保留此出处http://10541571.blog.51cto.com/10531571/1762099

原文:http://10541571.blog.51cto.com/10531571/1762099


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐