Linux:进程间通信——命名管道

命名管道

和匿名管道一样,命名管道也是在内核中开辟的一段缓存区,不过和匿名管道不同的是,这段缓存区是有标识符的,这也就意味着不同的进程,不需要有亲缘关系,只需要通过标识符就能找到该缓冲区了。

命名管道的创建

命令创建

命名管道可以从命令行上创建,命令行创建是使用下面这个命令:

mkfifo filename

在这里插入图片描述
"p"代表文件类型为管道文件
注意:该文件是不支持直接写的,该文件的作用是通过它我们可以找到内核中的创建的缓冲区

函数创建

相关函数:
mkfifo函数:

函数原型:
#include <sys/stat.h>

int mkfifo(const char *filename,, mode_t mode);
返回值:成功返回0,失败返回-1

代码:

 #include <stdio.h>
 #include <unistd.h>
 #include <sys/stat.h>
 
 int main()
 {
   int fifoid = mkfifo("./fifoTest",0664);
   if(fifoid < 0)
   {
     perror("mkfifo");
     return -1;                                                      
   }
   return 0;
 }

运行结果:
在这里插入图片描述
一个完整的例子:
这个例子在namePipe.c中先向缓冲区中写入了hello linux!然后再read.c中读出所写的内容。
namePipe.c

 #include <stdio.h>                                                
 #include <unistd.h>
 #include <fcntl.h>
 #include <sys/stat.h>
 
 int main()
 {
   int fifoid = mkfifo("./fifoTest",0664);
   if(fifoid < 0)
   {
     perror("mkfifo");
     return -1;
   }
   printf("创建成功!\n");
   int fd =  open("./fifoTest",O_RDWR | O_CREAT);
   if(fd < 0)
   {
     perror("open");
     return -1;
   }
   else 
   {
     ssize_t w_size = write(fd,"hello linux!",12);
     if(w_size < 0)
     {
       perror("write");
       return -1;
     }
     printf("write:%d",w_size);
   }
   while(1)
   {
     printf("wait!\n");
     sleep(1);
   }
   return 0;
 }           

read.c

 #include <stdio.h>
 #include <unistd.h>
 #include <fcntl.h>
 
 int main()
 {
   int fd = open("./fifoTest",O_RDONLY);
   if(fd < 0)
   {
     perror("open");
     return -1;
   }
   else
   {
     char *buf[1024] = {0};
     int ret = read(fd,buf,12);
     if(ret < 0)
     {
       perror("read");
       return -1;
     }
     printf("buf is : %s\n",buf);                                  
   }
   return 0;
 
 }

namePipe.c的运行结果:
在这里插入图片描述
另一个终端中read.c的运行结果:
在这里插入图片描述

特性

(1) 生命周期跟随进程
(2) 命名管道具有表示符
(3) 其它特性和匿名管道一样

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值