linux 匿名管道实例详解

时间:2021-09-23 20:20:58

linux中进程的一种通信方式——匿名管道

pipe函数建立管道

调用pipe函数时在内核中开辟一块缓冲区(称为管道)用于通信,它有一个读端一个写端,然后通过_pipe参数传出给用户程序两个文件描述符,_pipe[0]指向管道的读端,_pipe[1]指向管道的写端。所以管道在用户程序看起来就像一个打开的文件,通过read(_pipe[0]);或者write(_pipe[1]);向这个文件读写数据其实是在读写内核缓冲区。pipe函数调用成功返回0,调用失败返回-1。

1父进程调用pipe开辟管道,得到两个文件描述符指向管道的两端。

2. 父进程调用fork创建⼦进程,那么子进程也有两个文件描述符指向同一管道。

3. 父进程关闭管道读端,子进程关闭管道写端。父进程可以往管道里写,子进程可以从管道⾥读,管道是用环形队列实现的,数据从写端流入从读端流出,这样就实现了进程间通信

匿名管道间的通信是单向的,并且是、只能是具有血缘关系的进程间通信

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
 
int main()
{
  int _pipe[2];
  int ret = pipe(_pipe);
  if (ret < 0)
  {
    perror("pipe");
    return 1;
  }
  pid_t id = fork ();
  if (id<0)
  {
    perror("fork");
    return 2;
  }
  else if (id == 0)
  {
    // child
    int count =5;
    close (_pipe[0]);
    char* msg = "hello bit";
    while (count --)
    {
      write(_pipe[1],msg,strlen(msg));
      sleep(1);
    }
    close (_pipe[1]);
    exit(123);
  }
  else
  {
    // Father
    close(_pipe[1]);
    char buf[128];
    while(1)
    {
      int count =5;
      ssize_t s = read ( _pipe[0],buf,sizeof(buf)-1);
      if (s<0)
      {
        perror("read");
      }
      else if(s==0)
      {
        printf("write is close\n");
        return 2;
      }
      else
      {
        buf[s] ='\0';
        printf ("child >> father: %s\n",buf);
      }
      count --;
      if (count == 0)
      {
        close (_pipe[0]);
        break;
      }
    }
     
    int status = 0;
    pid_t _wait = waitpid (id, &status,0);
    if (_wait > 0)
    {
      printf("exit code is %d, signal is %d\n",
          WIFEXITED(status), status & 0xff);
    }
 
    }
     
  return 0;
}

linux 匿名管道实例详解

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/qq_35116353/article/details/59115323