当前位置:   article > 正文

【Linux】进程间通信 - 管道

【Linux】进程间通信 - 管道


在这里插入图片描述

1. 进程间通信介绍

两个进程间,可以进行“数据”的直接传递吗?不能!进程具有独立性!

进程间通信的本质:先让不同的进程,看到同一份资源(一般都是要由 OS 提供)。

1.1 进程间通信目的

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

1.2 进程间通信发展

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

1.3 进程间通信分类

  • 管道
    • 匿名管道 pipe
    • 命名管道
  • System V IPC
    • System V 消息队列
    • System V 共享内存
    • System V 信号量
  • POSIX IPC
    • 消息队列
    • 共享内存
    • 信号量
    • 互斥量
    • 条件变量
    • 读写锁

2. 管道

2.1 什么是管道

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

在这里插入图片描述

2.2 匿名管道

#include <unistd.h>

功能:创建一个无名管道
原型:
int pipe(int fd[2]);
参数:
fd:文件描述符数组,其中fd[0]表示读端,fd[1]表示写端
返回值:成功返回0,失败返回错误代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在这里插入图片描述

实例代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

// 例子:从键盘读取数据,写入管道,读取管道,写到屏幕
int main()
{
    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))
    {
        len = strlen(buf);
        // write into pipe
        if (write(fds[1], buf, len) != len)
        {
            perror("write to pipe");
            break;
        }
        memset(buf, 0x00, sizeof(buf));

        // 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;
        }
    }

    return 0;
}
  • 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

2.3 用 fork 来共享管道原理

在这里插入图片描述

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

在这里插入图片描述

2.5 站在内核角度 - 管道本质

在这里插入图片描述

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

fork 共享管道测试代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

// child
void writer(int wfd)
{
    const char *str = "hello father, I am child";
    char buffer[128];
    int cnt = 0;
    pid_t pid = getpid();
    while (1)
    {
        sleep(1);
        char c = 'A';
        write(wfd, &c, 1);
        cnt++;

        printf("cnt: %d\n", cnt);
    }
    close(wfd);
}

// father
void reader(int rfd)
{
    char buffer[1024];
    int cnt = 10;
    while (1)
    {
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
            printf("father get a message: %s, n: %ld\n", buffer, n);
        else if (n == 0)
        {
            printf("read pipe done, read file done!\n");
            break;
        }
        else
            break;

        cnt--;
        if (cnt == 0)
            break;
    }
    close(rfd);
    printf("read endpoint close!\n");
}

int main()
{
    printf("PIPE_BUF: %d\n", _PC_PIPE_BUF);

    // 1.
    int pipefd[2];
    int n = pipe(pipefd);
    if (n < 0)
        return 1;

    //                                       read       write
    printf("pipefd[0]: %d, pipefd[1]: %d\n", pipefd[0], pipefd[1]); // 3, 4

    // 2.
    pid_t id = fork();
    if (id == 0)
    {
        // child: w
        close(pipefd[0]);
        writer(pipefd[1]);
        exit(0);
    }

    // father: r
    close(pipefd[1]);
    reader(pipefd[0]);

    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if (rid == id)
    {
        printf("exit code: %d, exit signal: %d\n", WEXITSTATUS(status), status & 0x7F);
    }

    return 0;
}
  • 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
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88

2.6 管道读写规则

  1. 当没有数据可读时
    • O_NONBLOCK disable:read 调用阻塞,即进程暂停执行,一直等到有数据来到为止。
    • O_NONBLOCK enable:read 调用返回 -1,errno 值为 EAGAIN。
  2. 当管道满的时候
    • O_NONBLOCK disable:write 调用阻塞,直到有进程读走数据。
    • O_NONBLOCK enable:调用返回 -1,errno 值为 EAGAIN。
  3. 如果所有管道写端对应的文件描述符被关闭,则 read 返回 0。
  4. 如果所有管道读端对应的文件描述符被关闭,则 write 操作会产生信号 SIGPIPE,进而可能导致 write 进程退出。
  5. 当要写入的数据量不大于 PIPE_BUF 时,Linux 将保证写入的原子性。
  6. 当要写入的数据量大于 PIPE_BUF 时,Linux 将不再保证写入的原子性。

2.7 管道特点

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

在这里插入图片描述

3. 命名管道

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

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

    int mkfifo(const char* filename, mode_t mode);
    
    • 1

创建命名管道:

int main(int argc, char* argv[])
{
	mkfifo("p2", 0644);
	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5

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

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

3.2 命名管道的打开规则

  • 如果当前打开操作是为读而打开 FIFO 时:
    • O_NONBLOCK disable:阻塞直到有相应进程为写而打开该 FIFO。
    • O_NONBLOCK enable:立刻返回成功。
  • 如果当前打开操作是为写而打开 FIFO 时:
    • O_NONBLOCK disable:阻塞直到有相应进程为读而打开该 FIFO。
    • O_NONBLOCK enable:立刻返回失败,错误码为 ENXIO。

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

$ ls -l
total 16
-rw-rw-r-- 1 ubuntu ubuntu 1009 May  4 17:16 Comm.hpp
-rw-rw-r-- 1 ubuntu ubuntu  193 May  4 15:14 Makefile
-rw-rw-r-- 1 ubuntu ubuntu  656 May  4 17:44 PipeClient.cc
-rw-rw-r-- 1 ubuntu ubuntu  929 May  4 17:44 PipeServer.cc
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Makefile:

$ cat Makefile 
.PHONY:all
all:pipe_client pipe_server

pipe_server:PipeServer.cc
	g++ -o $@ $^ -std=c++11
pipe_client:PipeClient.cc
	g++ -o $@ $^ -std=c++11

.PHONY:clean
clean:
	rm -f pipe_client pipe_server
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Comm.hpp:

#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

using namespace std;

#define Mode 0666
#define Path "./fifo"

class Fifo
{
public:
    Fifo(const string &path)
        : _path(path)
    {
        umask(0);
        int n = mkfifo(_path.c_str(), Mode);
        if (n == 0)
        {
            cout << "mkfifo success" << endl;
        }
        else
        {
            cerr << "mkfifo failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        }
    }

    ~Fifo()
    {
        int n = unlink(_path.c_str());
        if (n == 0)
        {
            cout << "remove fifo file " << _path << " success" << endl;
        }
        else
        {
            cerr << "remove failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        }
    }

private:
    string _path; // 文件路径 + 文件名
};

#endif
  • 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

PipeServer.cc:

#include "Comm.hpp"

int main()
{
    Fifo fifo(Path);

    int rfd = open(Path, O_RDONLY);
    if (rfd < 0)
    {
        cerr << "open failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        return 1;
    }
    // 如果我们的写端没打开,先读打开,open的时候就会阻塞,直到把写端打开,读open才会返回
    cout << "open success" << endl;

    char buffer[1024];
    while (true)
    {
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "client sat : " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "client quit, me too!" << endl;
            break;
        }
        else
        {
            cerr << "read failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
            break;
        }
    }

    close(rfd);
    return 0;
}
  • 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

PipeClient.cc:

#include "Comm.hpp"

int main()
{
    int wfd = open(Path, O_WRONLY);
    if (wfd < 0)
    {
        cerr << "open failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        return 1;
    }

    string inbuffer;
    while (true)
    {
        cout << "Please Enter Your Message# ";
        std::getline(cin, inbuffer);
        if (inbuffer == "quit")
            break;

        ssize_t n = write(wfd, inbuffer.c_str(), inbuffer.size());
        if (n < 0)
        {
            cerr << "write failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
            break;
        }
    }

    close(wfd);
    return 0;
}
  • 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

结果:

在这里插入图片描述


END
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/632541
推荐阅读
相关标签
  

闽ICP备14008679号