linux 用命名管道实现进程间通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40921797/article/details/82665428

什么是命名管道

命名管道和匿名管道一样适用于进程之间的通信linux匿名管道详解,但是使用范围不同,匿名管道要求必须是亲缘进程,而命名管道却没有这个限制,它可以用于同一台机器主机上的任意进程间通信。

命名管道的创建 ,使用

  1. 命令创建 :可以通过命令行命令创建
    通过 mkfifo pipe_filename
  2. 代码创建:可以在函数里通过引用库函数创建
    通过
       #include <sys/types.h>
       #include <sys/stat.h>

       int mkfifo(const char *pathname, mode_t mode);
       //第一个参数,是命名管道的文件名字,
       //第二个参数,是要创建的这个文件的文件权限,我们为了我们给出的权限值,就是最终的权限,可以在之前修改一下文件创建掩码。
       //返回值:成功返回0,失败返回<0的值,这里还定义很多errno的宏作为返回值,为了帮助我们判断失败原因。例如:
       //EEXIST 文件已经存在了,所以创建失败pathname already exists. 

3.命名管道的使用,就是当作文件使用的。关于文件的open,write,read,close详细见博客文件io操作
通过一个程序,完成写,一个程序完成读。两个程序在两个进程下跑,来验证命名管道的使用方式。

//这个myfifo_r.c 是为了从命名管道中读取数据
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
//fcntl.h 是为了open,close等操作
int main
{
     umask(0);
     //创建命名管道
     if(mkfifo("./mytest.fifo",0664) < 0)
     {
         if(errno == EEXIST)
          {//文件已存在无需再次创建}
          else
          {
              perror("mkfifo error");
              return -1;
          }
      }
      //以只读方式打开O_RDONLY代表只读权限,类似见上文博客链接
      int fd = open("./mytest.fifo",O_RDONLY);
      if(fd < 0)
      {
          perror("open fifo error");
          return -1;
      }
      printf("mytest.fifo is open ,new you can read\n");
      while(1)
      {
          char buff[1024] = {0};
          int ret = read(fd,buff,1023);
          //ret=0代表没有读到东西,
          if(ret > 0)
          {
              printf("read:[%s]\n",buff);
          }
          else if(ret == 0)
          {
              printf("all write is close !!\n");
              sleep(1);
          }
      }
      close(fd);
      return 0;
  }
//这个myfifo_w.c 是为了向命名管道中写入数据
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
//fcntl.h 是为了open,close等操作
int main
{
     umask(0);
     //创建命名管道
     if(mkfifo("./mytest.fifo",0664) < 0)
     {
         if(errno == EEXIST)
          {//文件已存在无需再次创建}
          else
          {
              perror("mkfifo error");
              return -1;
          }
      }
      //以只读方式打开O_RDONLY代表只读权限,类似见上文博客链接
      int fd = open("./mytest.fifo",O_WRONLY);
      if(fd < 0)
      {
          perror("open fifo error");
          return -1;
      }
      printf("mytest.fifo is open ,new you can write\n");
      while(1)
      {
          char buff[1024] = {0};
          scanf("%s",buff);
          write(fd,buff,strlen(buff)+1);
      }
      close(fd);
      return 0;
  }

运行结果:
这里写图片描述

命名管道特点

1.
如果以只读read方式打开open命名管道,则阻塞式等待直到都其他进程以只写write的方式打开命名管道。
如果以只写write方式打开open命名管道,则阻塞式等待直到都其他进程以只读read的方式打开命名管道。
2.如果这个命名管道是以读写的方式打开,则不会阻塞式等待。
3.管道的生命周期随进程,进程结束,管道关闭
4.管道自带同步与互斥
5.和匿名管道不同,匿名管道创建后返回一个文件描述符给我们使用。
而命名关系需要我们用户自己打开关闭文件。

猜你喜欢

转载自blog.csdn.net/weixin_40921797/article/details/82665428