Linux_进程间通信

18fde01fee5e4278981004762ce48cc4.png

✨✨ 欢迎大家来到小伞的大讲堂✨✨

🎈🎈养成好习惯,先赞后看哦~🎈🎈

所属专栏:LInux_st
小伞的主页:xiaosan_blog

制作不易!点个赞吧!!谢谢喵!!

1.进程间通信介绍

1.1 进程间通信的目的

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

1.2 进程间通信发展

  • 管道
  • SystemV进程间通信
  • POSIX进程间通信

1.3 进程间通信分类

管道

  • 匿名管道pipe
  • 命名管道

System V IPC

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

POSIX IPC

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

2. 管道

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

3.匿名管道

#include <unistd.h>
功能:创建⼀⽆名管道
原型
int pipe(int fd[2]);
参数
fd:⽂件描述符数组,其中fd[0]表⽰读端, fd[1]表⽰写端
返回值:成功返回0,失败返回错误代码

3.1 实例代码

#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;
        }
        // 成功时:返回实际写入的字节数。
        // 失败时:返回-1,并将错误代码存入errno中。返回值为0表示没有写入任何数据,通常发生在count为0的情况下。
        memset(buf, 0x00, sizeof(buf));
        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;
}

3.2 用fork来共享管道

3.3 站在文件描述符角度看管道

3.4 站在内核看管道

3.5 管道样例

3.5.1 测试管道读写
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
//使用宏
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

int main()
{
    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;
}
3.5.2 创建进程池处理任务
channel.hpp
#ifndef __CHANNEL_HPP__
#define __CHANNEL_HPP__

#include <iostream>
#include <string>
#include <unistd.h>

class channel
{
public:
    channel(int wfd, pid_t who)
        : _wfd(wfd),
          _who(who)
    // Channel-3-1234
    // 文件描述符+pid 组成编号
    {
        _name = "Channel-" + std::to_string(wfd) + "-" + std::to_string(who);
    }
    std::string Name()
    {
        return _name;
    }

    void Send(int cmd)
    {
        write(_wfd, &cmd, sizeof(cmd));
    }

    void Close()
    {
        close(_wfd);
    }
    pid_t Id()
    {
        return _who;
    }
    int wfd()
    {
        return _wfd;
    }
    ~channel()
    {
    }

private:
    int _wfd;
    std::string _name;
    pid_t _who;
};

#endif
process_pool.hpp
#ifndef __PROCESS_POOL_HPP__
#define __PROCESS_POOL_HPP__

#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <functional>
#include "task.hpp"
#include "channel.hpp"

using work_t = std::function<void()>;

enum
{
    OK = 0,
    UsageError,
    PipeError,
    ForkError
};

class ProcessPool
{
public:
    ProcessPool(int n, work_t w)
        : processnum(n), work(w)
    {
    }

    int InitProcessPool()
    {
        for (int i = 0; i < processnum; i++)
        {
            // 1.创建管道
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
                return PipeError;
            // 2.创建进程
            pid_t id = fork();
            if (id < 0)
                return ForkError;
            // 3.建立通讯信道
            if (id == 0)
            {
                // 子进程
                // 关闭历史wfd
                std::cout << getpid() << ",chile close history fd";
                for (auto &c : channels)
                {
                    std::cout << c.wfd() << " ";
                    c.Close();
                }
                std::cout << "close over" << std::endl;
                close(pipefd[1]); // read
                std::cout << "debug:" << pipefd[0] << std::endl;
                dup2(pipefd[0], 0);
                work();
                exit(0);
            }
            close(pipefd[0]); // write
            channels.emplace_back(pipefd[1], id);
            // channel ch(pipefd[1], id);
            // channels.push_back(ch);
        }
        return OK;
    }
    void DispatchTask()
    {
        int who = 0;
        // 派发任务
        int num = 20;
        while (num--)
        {
            // 选择一个任务
            int task = tm.SelecTask();
            // 选择一个子进程channel
            channel &curr = channels[who++];
            who %= channels.size();

            std::cout << "######################" << std::endl;
            std::cout << "send " << task << " to " << curr.Name() << ", 任务还剩: " << num << std::endl;
            std::cout << "######################" << std::endl;
            // 发送任务
            curr.Send(task);

            sleep(1);
        }
    }

    void CleanProcessPool()
    {

        for (auto &c : channels)
        {
            c.Close();

            pid_t rid = ::waitpid(c.Id(), nullptr, 0);
            if (rid > 0)
            {
                std::cout << "child " << rid << " wait ... success" << std::endl;
            }
        }

        // for (auto &c : channels)
        // {
        //     c.Close();
        // }
        // for (auto &c : channels)
        // {
        //     pid_t rid = ::waitpid(c.Id(), nullptr, 0);
        //     if (rid > 0)
        //     {
        //         std::cout << "child " << rid << " wait ... success" << std::endl;
        //     }
        // }
    }
    void DebugPrint()
    {
        for (auto &c : channels)
        {
            std::cout << c.Name() << std::endl;
        }
    }

private:
    std::vector<channel> channels;
    int processnum;
    work_t work;
};

#endif
task.hpp
#pragma once

#include <iostream>
#include <unordered_map>
#include <functional>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>
#include <vector>

using task_t = std::function<void()>;

class TaskManger
{
public:
    TaskManger()
    {
        srand(time(nullptr));
        // lambda
        tasks.push_back([]()
                        { std::cout << "sub process[" << getpid() << " ] 执⾏访问数据库的任务\n"
                                    << std::endl; });
        tasks.push_back([]()
                        { std::cout << "sub process[" << getpid() << " ] 执⾏url解析\n"
                                    << std::endl; });
        tasks.push_back([]()
                        { std::cout << "sub process[" << getpid() << " ] 执⾏加密任务\n"
                                    << std::endl; });
        tasks.push_back([]()
                        { std::cout << "sub process[" << getpid() << " ] 执⾏数据持久化任务\n " << std::endl; });
    }

    int SelecTask()
    {
        return rand() % tasks.size();
    }

    void Excute(unsigned long number)
    {
        if (number > tasks.size() || number < 0)
            return;
        tasks[number]();
    }

    ~TaskManger()
    {
    }

private:
    std::vector<task_t> tasks;
};

TaskManger tm;

void Worker()
{
    while (true)
    {
        int cmd = 0;
        int n = read(0, &cmd, sizeof(cmd));
        if (n == sizeof(cmd))
        {
            tm.Excute(cmd);
        }
        else if (n == 0)
        {
            std::cout << "pid: " << getpid() << " quit..." << std::endl;
            break;
        }
        else
        {
        }
    }
}
main.cc
#pragma once

#include <iostream>
#include <unordered_map>
#include <functional>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>
#include <vector>

using task_t = std::function<void()>;

class TaskManger
{
public:
    TaskManger()
    {
        srand(time(nullptr));
        // lambda
        tasks.push_back([]()
                        { std::cout << "sub process[" << getpid() << " ] 执⾏访问数据库的任务\n"
                                    << std::endl; });
        tasks.push_back([]()
                        { std::cout << "sub process[" << getpid() << " ] 执⾏url解析\n"
                                    << std::endl; });
        tasks.push_back([]()
                        { std::cout << "sub process[" << getpid() << " ] 执⾏加密任务\n"
                                    << std::endl; });
        tasks.push_back([]()
                        { std::cout << "sub process[" << getpid() << " ] 执⾏数据持久化任务\n " << std::endl; });
    }

    int SelecTask()
    {
        return rand() % tasks.size();
    }

    void Excute(unsigned long number)
    {
        if (number > tasks.size() || number < 0)
            return;
        tasks[number]();
    }

    ~TaskManger()
    {
    }

private:
    std::vector<task_t> tasks;
};

TaskManger tm;

void Worker()
{
    while (true)
    {
        int cmd = 0;
        int n = read(0, &cmd, sizeof(cmd));
        if (n == sizeof(cmd))
        {
            tm.Excute(cmd);
        }
        else if (n == 0)
        {
            std::cout << "pid: " << getpid() << " quit..." << std::endl;
            break;
        }
        else
        {
        }
    }
}
Makefile
BIN=processpool
CC=g++
FLAGS=-c -Wall -std=c++11 #Wall -报警提示
LDFLAGS=-o
# SRC=$(shell ls *.cc)
SRC=$(wildcard *.cc) #返回当前目录下的所有.cc文件
OBJ=$(SRC:.cc=.o)

$(BIN):$(OBJ)
		$(CC) $(LDFLAGS) $@ $^
%.o:%.cc
		$(cc) $(FLAGS) $<

.PHONY:clean
clean:
		rm -rf $(BIN) $(OBJ)
.PHONY:test
test:
		@echo $(SRC)
		@echo $(OBJ)
3.6 管道读写规则

当没有数据可读时

  • O_NONBLOCKdisable:read调用阻塞,即进程暂停执行,一直等到有数据来到为止。
  • O_NONBLOCKenable:read调用返回-1,errno值为EAGAIN。

当管道满的时候

  • O_NONBLOCKdisable:write调用阻塞,直到有进程读走数据
  • O_NONBLOCKenable:调用返回-1,errno值为EAGAIN

如果所有管道写端对应的文件描述符被关闭,则read返回0

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

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

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

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

4.命名管道

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

4.1创建命名管道

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

$ mkfifo filename

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

nt mkfifo(const char *filename,mode_t mode) ;

创建命名管道

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

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

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

4.3 命名管道的打开规则

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

  • O_NONBLOCKdisable:阻塞直到有相应进程为写而打开该FIFO
  • O_NONBLOCKenable:立刻返回成功

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

  • O_NONBLOCKdisable:阻塞直到有相应进程为读而打开该FIFO
  • O_NONBLOCKenable:立刻返回失败,错误码为ENXIO
4.4 用命名管道实现文件拷贝

读取文件,写入命名管道:

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

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

int main(int argc, char *argv[])
{
    mkfifo("tp", 0644);
    int infd;
    infd = open("abc", O_RDONLY);
    if (infd == -1)
        ERR_EXIT("open");
    int outfd;
    outfd = open("tp", O_WRONLY | O_CREAT);
    if (outfd == -1)
        ERR_EXIT("open");
    char buf[1024];
    int n;
    while ((n = read(infd, buf, 1024)) > 0)
    {
        write(outfd, buf, n);
    }
    close(infd);
    close(outfd);
    return 0;
}

读取管道,写入目标文件:

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

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)
int main(int argc, char *argv[])
{
    int outfd;
    outfd = open("abc.bak", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (outfd == -1)
        ERR_EXIT("open");
    int infd;
    infd = open("tp", O_RDONLY);
    if (outfd == -1)
        ERR_EXIT("open");
    char buf[1024];
    int n;
    while ((n = read(infd, buf, 1024)) > 0)
    {
        write(outfd, buf, n);
    }
    close(infd);
    close(outfd);
    unlink("tp");
    return 0;
}

 读取文件

创建管道 ,写入管道

读取管道,写入目标文件 

4.5 命名管道实现服务端与客户端通信

clientPipe.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

int main()
{
    //写入管道
    int wfd = open("mypipe", O_WRONLY);
    if (wfd < 0)
    {
        ERR_EXIT("open");
    }
    char buf[1024];
    while (1)
    {
        buf[0] = 0;
        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 if (s <= 0)
        {
            ERR_EXIT("read");
        }
    }
    close(wfd);
    return 0;
}

serverPipe.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)
int main()
{
    umask(0);
    //创建管道
    if (mkfifo("mypipe", 0644) < 0)
    {
        ERR_EXIT("mkfifo");
    }
    //读取管道
    int rfd = open("mypipe", O_RDONLY);
    if (rfd < 0)
    {
        ERR_EXIT("open");
    }
    char buf[1024];
    while (1)
    {
        buf[0] = 0;
        printf("Please wait...\n");
        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("client quit, exit now!\n");
            exit(EXIT_SUCCESS);
        }
        else
        {
            ERR_EXIT("read");
        }
    }
    close(rfd);
    return 0;
}

Makefile

.PHONY:all
all:clientPipe serverPipe

clientPipe:clientPipe.c
	gcc -o $@ $^
serverPipe:serverPipe.c
	gcc -o $@ $^
.PHONY:clean
clean:
	rm -f clientPipe serverPipe
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值