ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

进程间通信——管道

2022-01-22 12:01:43  阅读:149  来源: 互联网

标签:pi int 间通信 管道 进程 include buf


文章目录

进程间通信介绍

进程间通信目的

  • 数据传输:一个进程需要将它的数据发送给另一个进程
  • 资源共享:多个进程之间共享同样的资源。
  • 通知事件:一个进程需要向另一个或一组进程发送消息,通知它(它们)发生了某种事件(如进程终止时要通知父进程)。
  • 进程控制:有些进程希望完全控制另一个进程的执行(如Debug进程),此时控制进程希望能够拦截另一个进程的所有陷入和异常,并能够及时知道它的状态改变。

进程间通信发展

  • 管道
  • System V进程间通信
  • POSIX进程间通信

进程间通信分类

管道

  • 匿名管道pipe
  • 命名管道

System V IPC

  • System V 消息队列
  • System V 共享内存
  • System V 信号量

POSIX IPC

  • 消息队列
  • 共享内存
  • 信号量
  • 互斥量
  • 条件变量
  • 读写锁

要让两个不同的进程实现通信,前提是让这两个进程看到同一份资源

管道

什么是管道

  • 管道是Unix中最古老的进程间通信的形式。
  • 我们把从一个进程连接到另一个进程的一个数据流称为一个“管道 ”

匿名管道

#include <unistd.h>
功能:创建一个无名管道
函数原型
int pipe(int fd[2]);
参数
fd:文件描述符数组,其中fd[0]表示读端, fd[1]表示写端
返回值:成功返回0,失败返回-1

image-20211006014034149

实例代码

//例子:从键盘读取数据,写入管道,读取管道,写到屏幕
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main( void )
{
    int fds[2];
    char buf[100];
    int len;
    
    if ( pipe(fds) == -1 )//创建匿名管道
    	perror("make pipe"),exit(1);
    
    // read from stdin
    while ( fgets(buf, 100, stdin) ) //循环向buf中写数据
    {
        len = strlen(buf);
        
        // write into pipe
        //先写再判断
        if (write(fds[1], buf, len) != len) //当实际写入管道的字符个数不等于buf长度时,就写入错误
        {
            perror("write to pipe");
            break;
        }
        
        memset(buf, 0x00, sizeof(buf));//将buf的内容置为0
        
        // read from pipe
        if ( (len=read(fds[0], buf, 100)) == -1 ) //先读再判断
        {
            perror("read from pipe");
            break;
        }
        
        // write to stdout
        if ( write(1, buf, len) != len ) //先写再判断
        {
            perror("write to stdout");
            break;
        }
        
    }
}

用fork来共享管道原理

image-20211006015013478

站在文件描述符角度-深度理解管道

因为我们最开始的进程打开了标准输入、标准输出、标准错误三个文件,所以之后所有的进程都默认打开这三个文件

为什么文件不会各自私有?因为文件是不属于进程的

image-20211006021646696

站在内核角度-管道本质

image-20211006023255188

f_op就是我们之前说的函数指针。

图是简化理解的,inode指针并不在struct file中

所以,看待管道,就如同看待文件一样!管道的使用和文件一致,迎合了“Linux一切皆文件思想” 。

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define ERR_EXIT(m) \ do \ { \ perror(m); \ exit(EXIT_FAILURE); \ } while(0)
int main(int argc, char *argv[])
{ 	
    int pipefd[2]; 
    if (pipe(pipefd) == -1) 
        ERR_EXIT("pipe error");
    
    pid_t pid;
	pid = fork();
    if (pid == -1)
    	ERR_EXIT("fork error");
    
    if (pid == 0) //子进程
    {
        close(pipefd[0]);//关闭读端
        
        //向管道写入
        write(pipefd[1], "hello", 5);
        //关闭写端,减少文件描述符的占用
        close(pipefd[1]);
        exit(EXIT_SUCCESS);
    }
    
    //父进程关闭写端
    close(pipefd[1]);
    
    char buf[10] = {0};
    //从管道中读数据
    read(pipefd[0], buf, 10);
    printf("buf=%s\n", buf);
    
    return 0;
}

管道读写规则

  1. 如果写端不关闭文件描述符,也不写入,读端可能会阻塞很长时间(可能管道中一开始就有数据,不会立马就阻塞)

    示例:

    #include<stdio.h>
    #include <unistd.h>
    #include<string.h>
    
    
    int main()
    {
      int pi[2] = {0};
      if (pipe(pi) < 0)//创建匿名管道失败
      {
        perror("pipe");
        return 1;
      }
      
      int pid = fork();
      if (pid < 0)
      {
        perror("fork");
        return 1;
      }
      
      //让子进程写,父进程读  
      if (pid == 0)//子进程
      {
        //怕失误使用了另一个接口,所以关闭子进程的读
        close(pi[0]);
    
        const char* buf = "I am a child!\n";
    
        while (1)
        {
          write(pi[1], buf, strlen(buf));
          sleep(3);//子进程每隔3s才写入
        
        }
      }
      else//父进程,只读 
      {
        close(pi[1]);
        char buf[64];
        while (1)
        {
          ssize_t s = read(pi[0], buf, sizeof(buf) - 1);
          
          if (s > 0)
          {
            buf[s] = 0;
          }
    
          printf("father get info from pipe:%s\n", buf);
        
        } 
      }
    
      return 0;
    }
    
    

    因为子进程每隔3s才写入管道,而父进程则是无间断地读取管道数据,所以相对来说父进程会阻塞一段时间:

    匿名管道1

    所以,如果我们关闭了子进程的文件描述符,父进程就会一直在等待,也就是陷入长时间的阻塞。

  2. 当我们写入时,如果写入条件不满足(管道满了,读端读取速度太慢),写入端就会阻塞

    #include<stdio.h>
    #include <unistd.h>
    #include<string.h>
    
    
    int main()
    {
      int pi[2] = {0};
      if (pipe(pi) < 0)//创建匿名管道失败
      {
        perror("pipe");
        return 1;
      }
      
      int pid = fork();
      if (pid < 0)
      {
        perror("fork");
        return 1;
      }
      
      //让子进程写,父进程读  
      if (pid == 0)//子进程
      {
        //怕失误使用了另一个接口,所以关闭子进程的读
        close(pi[0]);
    
        const char* buf = "I am a child!\n";
        
        int count = 0;
        while (1)
        {
          
          write(pi[1], buf, strlen(buf));
          printf("CHILD:%d\n", count++);
        }
      }
      else//父进程,只读 
      {
        close(pi[1]);
        char buf[64];
        while (1)
        {
          ssize_t s = read(pi[0], buf, sizeof(buf) - 1);
          sleep(1);//父进程每隔1s读一次
    
          if (s > 0)
          {
            buf[s] = 0;
          }
            
          printf("father get info from pipe:%s\n", buf);
        
        } 
      }
    
      return 0;
    }
    

    可以看到,子进程一开始就在猛地写入,而父进程每隔1s才读一次数据,并且从父进程开始读数据,子进程就没有再写入了,是因为管道满了,写入条件不满足,无法完成写入。

    匿名管道2

  3. 如果写端关闭文件描述符,读端在读取管道时会读到0,也就是read函数返回0

    #include<stdio.h>
    #include <unistd.h>
    #include<string.h>
    
    
    int main()
    {
      int pi[2] = {0};
      if (pipe(pi) < 0)//创建匿名管道失败
      {
        perror("pipe");
        return 1;
      }
      
      int pid = fork();
      if (pid < 0)
      {
        perror("fork");
        return 1;
      }
      
      //让子进程写,父进程读  
      if (pid == 0)//子进程
      {
        //怕失误使用了另一个接口,所以关闭子进程的读
        close(pi[0]);
    
        const char* buf = "I am a child!\n";
        
        int count = 0;
        while (1)
        {
          if (count == 5)//子进程只写入5次
            close(pi[1]);
    
          write(pi[1], buf, strlen(buf));
          ++count;
        }
      }
      else//父进程,只读 
      {
        close(pi[1]);
        char buf[64];
        while (1)
        {
          ssize_t s = read(pi[0], buf, sizeof(buf) - 1);
          sleep(1);//父进程休眠1s再读取
    
          if (s > 0)
          {
            buf[s] = 0;
            
          	printf("father get info from pipe:%s\n", buf);
          }
          printf("father exit return : %d\n", s);
        } 
    
      }
    
      return 0;
    }
    
    

    子进程无休眠地只写入5次,而父进程休眠1s读取一次,当子进程停止写入后,父进程从管道中读取的数据就为0了。

    匿名管道3

  4. 如果读端关闭,写端进程可能直接被杀掉

    #include<stdio.h>
    #include <unistd.h>
    #include<string.h>
    #include<stdilb.h>
    
    int main()
    {
      int pi[2] = {0};
      if (pipe(pi) < 0)//创建匿名管道失败
      {
        perror("pipe");
        return 1;
      }
      
      int pid = fork();
      if (pid < 0)
      {
        perror("fork");
        return 1;
      }
      
      //让子进程写,父进程读  
      if (pid == 0)//子进程
      {
        //怕失误使用了另一个接口,所以关闭子进程的读
        close(pi[0]);
    
        const char* buf = "I am a child!\n";
        
        int count = 0;
        while (1)
        {
    		
          write(pi[1], buf, strlen(buf));
        	printf("CHILD:%d\n", count++);
        }
    
        exit(2);
      }
      else//父进程,只读 
      {
        close(pi[1]);
        char buf[64];
        int count = 0;
        while (1)
        {
          if (5 == count++)
          {   
              close(pi[0]);
          	  break;
          }
          ssize_t s = read(pi[0], buf, sizeof(buf) - 1);
          sleep(1);
    
          if (s > 0)
          {
            buf[s] = 0;
          	printf("father get info from pipe:%s\n", buf);
          }
    
        } 
    
      }
    
      return 0;
    }
    
    

    初步观察:

匿名管道4.1

我们看到在父进程读取5次后,父子进程都结束了,子进程也没有继续打印了,而是退出了。

我们不让父进程结束,再来用脚本来观察父子进程的状态:

shell脚本:

   while :; do ps axj |grep mypipe | grep -v grep; echo "######################################"; sleep 1; done

效果:

匿名管道4.2

可以看到实际上子进程是处于僵尸状态了,也就是退出了。

实际上,它是被操作系统杀掉了,因为管道里面已经没人读数据了,而子进程还往管道里面写数据是在浪费资源,操作系统不允许这种行为发生,于是,就杀掉了子进程。

既然子进程是被杀掉的,就需要用父进程回收,并且获取它的信号

修改一下代码,让父进程等待,并且获取信号:

匿名管道4.2

可以看到子进程的退出信号是13

我们使用kill -l查看一下kill的13号命令:

image-20211006001505386

顾名思义,该信号是用来杀死管道相关的进程的。

修改代码:

   #include<stdio.h>
   #include <unistd.h>
   #include<string.h>
   #include<stdlib.h>
   #include<sys/wait.h>
   
   int main()
   {
     int pi[2] = {0};
     if (pipe(pi) < 0)//创建匿名管道失败
     {
       perror("pipe");
       return 1;
     }
     
     int pid = fork();
     if (pid < 0)
     {
       perror("fork");
       return 1;
     }
     
     //让子进程写,父进程读  
     if (pid == 0)//子进程
     {
       //怕失误使用了另一个接口,所以关闭子进程的读
       close(pi[0]);
   
       const char* buf = "I am a child!\n";
       
       int count = 0;
       while (1)
       {
   
         write(pi[1], buf, strlen(buf));
         printf("CHILD:%d\n", count++);
       }
   
       exit(2);
     }
     else//父进程,只读 
     {
       close(pi[1]);
       char buf[64];
       int count = 0;
       while (1)
       {
         if (5 == count++)
         { 
           close(pi[0]);
           break;
         }
         
         ssize_t s = read(pi[0], buf, sizeof(buf) - 1);
         sleep(1);
   
         if (s > 0)
         {
           buf[s] = 0;
           printf("father get info from pipe:%s\n", buf);
       
         }
         
       } 
   
         //父进程获取子进程的退出信号
         int status = 0;
         waitpid(pid, &status, 0);
         printf("child exited, father gets the signal:%d\n", status & 0x7f);
     }
   
     return 0;
   }
   

命令行中的 | 管道中,进程间是兄弟关系

我们使用sleep 2000 | sleep 1000命令运行,再复制一个会话查看它们的进程pid信息:

image-20211006002002190

  • 当没有数据可读时

    • O_NONBLOCK disable:read调用阻塞,即进程暂停执行,一直等到有数据来到为止。
    • O_NONBLOCK enable:read调用返回-1,errno值为EAGAIN。
  • 当管道满的时候

    • O_NONBLOCK disable: write调用阻塞,直到有进程读走数据
    • O_NONBLOCK enable:调用返回-1,errno值为EAGAIN
  • 如果所有管道写端对应的文件描述符被关闭,则read返回0

  • 如果所有管道读端对应的文件描述符被关闭,则write操作会产生信号SIGPIPE,进而可能导致write进程
    退出

  • 当要写入的数据量不大于PIPE_BUF时,linux将保证写入的原子性。

  • 当要写入的数据量大于PIPE_BUF时,linux将不再保证写入的原子性。

管道特点

  • 只能用于具有共同祖先的进程(具有亲缘关系的进程)之间进行通信;通常,一个管道由一个进程创
    建,然后该进程调用fork,此后父、子进程之间就可应用该管道。
  • 管道提供流式服务
  • 一般而言,进程退出,管道释放,所以管道的生命周期随进程
  • 一般而言,内核会对管道操作进行同步与互斥
  • 管道是半双工的,数据只能向一个方向流动;双方通信时,需要建立起两个管道

image-20211102131759476

匿名管道的进程间是兄弟关系

命名管道

  • 管道应用的一个限制就是只能在具有共同祖先(具有亲缘关系)的进程间通信。
  • 如果我们想在不相关的进程之间交换数据,可以使用FIFO文件来做这项工作,它经常被称为命名管道。
  • 命名管道是一种特殊类型的文件

创建一个命名管道

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

    $ mkfifo filename
    
  • 命名管道也可以从程序里创建,相关函数有 :

    int mkfifo(const char *filename, mode_t mode);
    //filename就是管道名
    
  • 创建命名管道:

    int main(int argc, char *argv[])
    {
        mkfifo("p2", 0644);
        return 0;
    }
    

匿名管道与命名管道的区别

  • 匿名管道由pipe函数创建并打开。
  • 命名管道由mkfifo函数创建,打开用open
  • FIFO(命名管道)与pipe(匿名管道)之间唯一的区别在它们创建与打开的方式不同,一但这些工作完
    成之后,它们具有相同的意义

命名管道的打开规则

  • 如果当前打开操作是为读而打开FIFO时

    • O_NONBLOCK disable:阻塞直到有相应进程为写而打开该FIFO
    • O_NONBLOCK enable:立刻返回成功
  • 如果当前打开操作是为写而打开FIFO时

    • O_NONBLOCK disable:阻塞直到有相应进程为读而打开该FIFO
    • O_NONBLOCK enable:立刻返回失败,错误码为ENXIO

用命名管道实现server&client通信

makefile

# ll
total 12
-rw-rw-r-- 1 ysj ysj 568 Oct  6 01:18 client.c
-rw-rw-r-- 1 ysj ysj 138 Oct  6 01:07 makefile
-rw-rw-r-- 1 ysj ysj 662 Oct  6 01:15 server.c

# cat Makefile
.PHONY:all
all:server client 

server:server.c
	gcc $^ -o $@
client:client.c
	gcc $^ -o $@

.PHONY:clean
clean:
	rm -f server client fifo

server.c

#include<stdio.h>
#include<string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>

#define FIFE_FIFO "fifo"

int main()
{
  umask(0);
  mkfifo(FIFE_FIFO, 0666);
  
  int rfd = open(FIFE_FIFO, O_RDONLY);
  if (rfd < 0)
  {
    perror("open");
    return 1;
  }
  
  char buf[64];

  while (1)
  {
    buf[0] = 0;
    printf("p")
    ssize_t s = read(rfd, buf, sizeof(buf) - 1);
    if (s > 0)
    {
        buf[s - 1]= 0;
        printf("client say:# %s\n", buf);
        
    }
    else if(s == 0) 
    {
      printf("exit,too\n");
      break; 
    }
    else {
      perror("read");
      return 1;
    }
    
  }

  close(rfd);
  return 0;
}

client.c

#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define FIFE_FIFO "fifo"

int main()
{
  
  int wfd = open(FIFE_FIFO, O_WRONLY);
  if (wfd < 0)
  {
    perror("open");
    return 1;
  }
  
  char buf[64];

  while (1)
  {
    printf("Please Enter:# ");
    fflush(stdout);
      
    ssize_t s = read(0, buf, sizeof(buf) - 1);
    if (s > 0)
    {
      buf[s]= 0;
      write(wfd, buf, strlen(buf));
    }
    else 
    {
      printf("exit\n");
      break; 
    }
    
  }

  close(wfd);
  return 0;
}

结果:

server和client

为什么一开始没有打印please wait…呢?
因为在server中,open的时候读端没有打开,就被阻塞在了open处,等到client开始运行,写端打开,所以server结束阻塞,开始运行,才打印了please wait…

servet和client没有关系,所以命名管道与匿名管道在这一点上不同:

image-20211006013029520

标签:pi,int,间通信,管道,进程,include,buf
来源: https://blog.csdn.net/aaaaaaaWoLan/article/details/122635184

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有