【Linux】进程间通信——管道


一、管道是什么?

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

二、匿名管道

头文件: #include <unistd.h>
函数声明: int pipe(int pipefd[2]);

  • 返回值: 成功调用返回 0, 失败返回 -1, 并且错误码被设置
  • pipefd: 输出型参数, 传入一个文件描述符数组, 调用成功后, 数组存储匿名管道文件的读写端, pipefd[0] 为读端, pipefd[1] 为写端

首先来看一下 pipefd 中存储的值为何:

#include <iostream>
#include <cassert>
#include <unistd.h>
using namespace std;

int main()
{
    int pipefd[2] = {0}; //定义文件描述符数组
    int n = pipe(pipefd); //创建匿名管道
    assert(n == 0); //检查创建是否成功
    // 查看fd
    cout << "pipefd[0]: " << pipefd[0] << endl;
    cout << "pipefd[1]: " << pipefd[1] << endl;
	return 0;
}

运行结果:
在这里插入图片描述
不出所料, 因为每个进程默认打开 0, 1, 2 号 fd, 所以顺延往后就是 3, 4 号了, 而 3 号 fd 也就是匿名管道的读端, 通过访问 3 号 fd 可以从匿名管道中读取数据, 4 号 fd 也就是匿名管道的写端, 通过访问 4 号 fd 可以向匿名管道中写入数据.

分四种情况讨论匿名管道:
四种情况的前提都是子进程向匿名管道写入, 父进程从匿名管道读取.

  1. 写的速度大于读的速度
#include <iostream>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main()
{
    int pipefd[2] = {0}; //定义文件描述符数组
    int n = pipe(pipefd); //创建匿名管道
    assert(n == 0); //检查创建是否成功
    
    pid_t pid = fork(); //创建子进程
    //子进程执行
    if (pid == 0)
    {
        close(pipefd[0]); //关闭子进程的读端
        int cnt = 1;
        while (true)
        {
            char buf[1024] = {'\0'};
            snprintf(buf, sizeof(buf), "[%d]I am ChildProcess,my pid is %d", cnt++, getpid());
        	write(pipefd[1], buf, strlen(buf));
        }
        close(pipefd[1]); //执行结束,关闭子进程的写端
        return 0;
    }
    
    close(pipefd[1]); // 关闭父进程的写端
    while(true)
    {
    	sleep(3);
        char buf[1024] = {'\0'};
        read(pipefd[0], buf, sizeof(buf));
        cout << "Show Message: " << buf << endl;
    }
    
    close(pipefd[0]); //执行结束,关闭父进程的读端
    int status = 0;
    waitpid(pid, &status, 0); // 等待子进程退出
    // 正常退出,输出退出码
    if (WIFEXITED(status))
    {
        cout << "Exit code is " << WEXITSTATUS(status) << endl;
    }
    // 异常退出,输出终止信号
    else
    {
        cout << "Termination signal is " << (status & 0x7f) << endl;
    }

	return 0;
}

运行结果:
在这里插入图片描述
在父进程没读取之前, 子进程疯狂的往匿名管道写入数据, 等父进程开始读取时, 会直接把子进程写的都读走, 而如果子进程已经把文件写满了还没有被读取, 那么会处于阻塞, 直到有进程读走数据.

  1. 写的速度小于读的速度
#include <iostream>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main()
{
    int pipefd[2] = {0}; //定义文件描述符数组
    int n = pipe(pipefd); //创建匿名管道
    assert(n == 0); //检查创建是否成功
    
    pid_t pid = fork(); //创建子进程
    //子进程执行
    if (pid == 0)
    {
        close(pipefd[0]); //关闭子进程的读端
        int cnt = 1;
        while (true)
        {
            sleep(100);      
            char buf[1024] = {'\0'};
            snprintf(buf, sizeof(buf), "[%d]I am ChildProcess,my pid is %d", cnt++, getpid());
            write(pipefd[1], buf, strlen(buf));
        }
        close(pipefd[1]); //执行结束,关闭子进程的写端
        return 0;
    }
    
    close(pipefd[1]); // 关闭父进程的写端
    while(true)
    {
    	char buf[1024] = {'\0'};
        read(pipefd[0], buf, sizeof(buf));
        cout << "Show Message: " << buf << endl;
    }
    
    close(pipefd[0]); //执行结束,关闭父进程的读端
    int status = 0;
    waitpid(pid, &status, 0); // 等待子进程退出
    // 正常退出,输出退出码
    if (WIFEXITED(status))
    {
        cout << "Exit code is " << WEXITSTATUS(status) << endl;
    }
    // 异常退出,输出终止信号
    else
    {
        cout << "Termination signal is " << (status & 0x7f) << endl;
    }

	return 0;
}

运行结果:
在这里插入图片描述
如果父进程读的很快, 文件里的数据都被读走了, 而此时子进程写的很慢, 那么在文件中已经没有数据可读的情况下, 父进程会阻塞, 直到有数据可读.

  1. 写端在写入5条数据后关闭,读端一直读
#include <iostream>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main()
{
    int pipefd[2] = {0}; //定义文件描述符数组
    int n = pipe(pipefd); //创建匿名管道
    assert(n == 0); //检查创建是否成功
    
    pid_t pid = fork(); //创建子进程
    //子进程执行
    if (pid == 0)
    {
        close(pipefd[0]); //关闭子进程的读端
        int cnt = 1;
        while (cnt <= 5)
        {    
            sleep(1);
            char buf[1024] = {'\0'};
            snprintf(buf, sizeof(buf), "[%d]I am ChildProcess,my pid is %d", cnt++, getpid());
            write(pipefd[1], buf, strlen(buf));
        }
        close(pipefd[1]); //执行结束,关闭子进程的写端
        return 0;
    }
    
    close(pipefd[1]); // 关闭父进程的写端
    while(true)
    {
    	sleep(1);
        char buf[1024] = {'\0'};
        int n = read(pipefd[0], buf, sizeof(buf));
        if(n == 0)
        {
        	break;
        }
        cout << "[" << cnt++ << "]Show Message: " << buf << endl;
    }
    
    close(pipefd[0]); //执行结束,关闭父进程的读端
    int status = 0;
    waitpid(pid, &status, 0); // 等待子进程退出
    // 正常退出,输出退出码
    if (WIFEXITED(status))
    {
        cout << "Exit code is " << WEXITSTATUS(status) << endl;
    }
    // 异常退出,输出终止信号
    else
    {
        cout << "Termination signal is " << (status & 0x7f) << endl;
    }

	return 0;
}

运行结果:
在这里插入图片描述

如果写端已经关闭, 那么读端会一直读到 0, 可以考虑在读端读到 0 时认为写端已经关闭, 那么读端也没有再继续读取的必要了, 可以直接退出, 把读端也关闭了.

  1. 读端在读取5条数据后关闭,写端一直写
#include <iostream>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main()
{
    int pipefd[2] = {0}; //定义文件描述符数组
    int n = pipe(pipefd); //创建匿名管道
    assert(n == 0); //检查创建是否成功
    
    pid_t pid = fork(); //创建子进程
    //子进程执行
    if (pid == 0)
    {
        close(pipefd[0]); //关闭子进程的读端
        int cnt = 1;
        while (true)
        {    
            sleep(1);
            char buf[1024] = {'\0'};
            snprintf(buf, sizeof(buf), "[%d]I am ChildProcess,my pid is %d", cnt++, getpid());
            write(pipefd[1], buf, strlen(buf));
        }
        close(pipefd[1]); //执行结束,关闭子进程的写端
        return 0;
    }
    
    close(pipefd[1]); // 关闭父进程的写端
    int cnt = 1;
    while(cnt <= 5)
    {
    	sleep(1);
        char buf[1024] = {'\0'};
        read(pipefd[0], buf, sizeof(buf));
        cout << "[" << cnt++ << "]Show Message: " << buf << endl;
    }
    
    close(pipefd[0]); //执行结束,关闭父进程的读端
    int status = 0;
    waitpid(pid, &status, 0); // 等待子进程退出
    // 正常退出,输出退出码
    if (WIFEXITED(status))
    {
        cout << "Exit code is " << WEXITSTATUS(status) << endl;
    }
    // 异常退出,输出终止信号
    else
    {
        cout << "Termination signal is " << (status & 0x7f) << endl;
    }

	return 0;
}

运行结果:
在这里插入图片描述
当读端关闭时, 如果写端还一直在写的话, 系统会向写端的进程发送 13 号信号 SIGPIPE 来终止该进程.

匿名管道的特点:

  • 只能用于具有亲缘关系的进程之间进行通信, 一般一个管道由一个进程创建, 然后该进程调用 fork, 通过子进程继承看到相同的 fd, 以此进行通信
  • 管道是半双工通信的, 数据只能向一个方向流动, 即一方写入, 另一方只能读取, 需要全双工通信时, 需要建立两个管道

三、命名管道

头文件:
#include <sys/types.h>
#include <sys/stat.h>

函数声明: int mkfifo(const char *pathname, mode_t mode);

  • 返回值: 成功调用返回 0, 失败返回 -1, 并且错误码被设置
  • pathname: 命名管道文件
  • mode: 命名管道文件访问权限

示例代码:
测试场景: 两个不相关的进程 server 和 client 想要进行通信, 建立通信条件并且进行通信, 让 server 进程进行写入操作, 然后 client 进行读取操作.
先创建一个两个进程都会包含的头文件:

#pragma once
#include <iostream>
#include <cassert>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
using namespace std;

#define MODE 0666
string path_name = "./fifo";

包含了一些会用到的头文件, 还有方便统一修改的宏.

接着编写 server.cpp:

#include "config.h"

//向client写入数据
int main()
{
    umask(0); //修改权限掩码
    int n = mkfifo(path_name.c_str(), MODE); //创建命名管道
    assert(n == 0);
    int fd = open(path_name.c_str(), O_WRONLY); //以只写的方式打开命名管道
    while(1)
    {
        cout << "Enter: ";
        char buf[1024] = {'\0'};
        cin >> buf;
        int n = write(fd, buf, sizeof(buf));
        if(n == 0)
        {
            continue;
        }
    }  

	unlink(path_name.c_str());
    return 0;
}

client.cpp:

#include "config.h"

int main()
{
    int fd = open(path_name.c_str(), O_RDONLY); //以只读的方式打开命名管道
    while(1)
    {
        char buf[1024] = {'\0'};
        int n = read(fd, buf, sizeof(buf));
        assert(n != -1);
        if(n == 0)
        {
            break;
        }
        cout << "client: " << buf << endl;
    }
    return 0;
}

若两个进程想要互相通信, 那么只需要一个进程来创建命名管道文件即可, 在创建了一个命名管道文件后, 另一个进程只需要打开该命名管道文件即可进行访问, 如上案例就是 server.cpp 创建一个命名管道文件并且以写的方式打开了该文件, 而命名管道文件已经被 server.cpp 创建出来了, 那么 client.cpp 只需要以读的方式打开该文件, 两个进程即可开始通信.

运行结果:
先来看看创建的命名管道文件:
在这里插入图片描述
通信结果:
在这里插入图片描述
在 server 中输入后按回车, 信息即可回显在 client 中, 终止进程 server 后, unlink() 会删除命名管道文件.


  • 21
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值