Linux:使用匿名管道对进程池的模拟实现

目录

一、Makefile

二、processpool.cc

2.1创建通信管道和子进程

 2.2控制子进程

 2.3回收进程

三、task.hpp

 四、完整代码


接下来我们将模拟实现一个进程池,进程池广泛应用与各个领域和方向,比如我们打开电脑后同时打开很多个进程(也就是软件),此时就要操作系统就要对进程进行管理,并且让每个进程去运行各自所对应的功能,今天我们无法实现如此庞大的功能,但可以通过模拟来熟悉和了解进程池是什么有什么作用以及其底层的运行原理。博主将通过匿名管道的方式,经过层层封装、层层调用来一步步实现一个小型的迷你进程池。

一、Makefile

processpool:processpool.cc
	g++ -o $@ $^ -std=c++11 -g
.PHONY:clean
clean:
	rm -f processpool

二、processpool.cc

首先需要构建出我们整个进程池的主体框架结构和功能。我们生成.exe文件后通过./processpool来进行运行,此时我们可以通过在main函数中显示写命令行参数列表来进行传参从而控制创建进程的数量,argv中存放我们输入的命令,在输入时用空格作为分隔符可以通过./process num传参给main函数,num就是我们要创建的进程的个数,此时argc所对应的就是argv中元素的个数,我们判断符合要求后就去创建通信信道和子进程。

int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        Usage(argv[0]);
        return UsageError;
    }
    int sub_process_num=stoi(argv[1]);
    if(sub_process_num<=0)
    return ArgError;
    srand((uint64_t)time(nullptr));

    //1.创建通信信道和子进程
    ProcessPool *processpool_ptr=new ProcessPool(sub_process_num);
    processpool_ptr->CreateProcess(worker);
    //2.控制子进程
    CtrlProcessPool(processpool_ptr,10);

    cout<<"task run done"<<endl;

    sleep(100);

    //3.回收进程

    delete processpool_ptr;

    return 0;
}

        管道由父进程创建并打开两个文件描述符,012都被占用的情况下,在第一次进行创建时pipe打开的fd是3和4,子进程继承父进程时会将文件描述符表也一并继承下来,父进程要写就必须关闭读端,子进程要读就需要关闭写端。

 

 可此时父进程在循环的进行创建管道和子进程, 而文件描述符fd的分配规则也是从前往后找有空位的地方依次往后进行分配,而刚刚父进程已经关闭了读端即fd为3所指向的文件,所以现在3号下标是空的,而父进程再次去创建下一个管道和进程时就会出现如下的情况:

pipe[0]即读端中的值依然是3 ,pipe[1]即写端中的值则是5,子进程依旧会继承父进程的两个读写端,然后依旧是父进程关闭读端,子进程关闭写端。

所以接下来继续创建就会反复出现子进程读端是3的情况。而父进程的写端则会依次4567创建下去。 同样的,子进程在继承父进程时会连同文件描述符表一起进行继承:同样,上一个管道的写端也会被新创建的子进程继承下来

此时的管道就不是真正意义上的单向管道了,随着父进程打开的文件描述符越来越多,就会导致后面创建的子进程就都会将之前打开的写端都继承下去。

而想要解决这种情况可以通过两种方式:

1、倒着关闭管道写端描述符,根据操作系统的规则,写端(父进程)没有被关闭时,读端(子进程)就会阻塞等待,而写端一旦被完全关闭,读端就会立马退出。而关闭写端时关闭的实际上时写端的引用计数,当引用计数为0时,写端才会被完全关闭。而之所以倒着关闭就是因为最后一个创建的channel的写端一定只有一个,此时倒着关闭写端的文件描述符后子进程就会退出,退出时连带着子进程的文件描述符表也会一并销毁,此时原本子进程中指向之前从父进程继承下来的其他管道的写端描述符的引用计数都会--,父进程依次倒着关闭写端,到第一个管道时,它就只剩下一个写端了。

2、在创建子进程时就关闭父进程曾经历史打开的写端描述符,这样每个子进程就只对应一个读端,每个管道也只对应一个写端。(博主用的是第二种方法)。

2.1创建通信管道和子进程

//1.创建通信信道和子进程
class ProcessPool
{
public:
    ProcessPool(int sub_process_num):_sub_process_num(sub_process_num)
    {}
    int CreateProcess(work_t work)//回调函数
    {
        vector<int> fds;
        for(int number=0;number<_sub_process_num;number++)
        {
            int pipefd[2]{0};
            int n=pipe(pipefd);
            if(n<0) return PipeError;

            pid_t id=fork();
            //子进程执行关闭写端,去读
            if(id==0)
            {
                //把父进程历史打开的写端关闭
                if(!fds.empty())
                {
                    cout<<"close w_fd:";
                    for(auto fd:fds) 
                    {
                        close(fd);
                        cout<<fd<<" ";
                    }
                    cout<<endl;
                }
                //child -> r
                close(pipefd[1]);
                //执行任务

                //为什么要dup2重定向:
                //原本从标准输入中读,变成从管道中读,
                //也就是此时当前子进程fd0中存放的就是当前管道的地址
                //之后通过访问标准输入就可以读到管道中的内容。
                dup2(pipefd[0],0);
                work(pipefd[0]);
                exit(0);
            }

            string cname="channel-"+to_string(number);
            //father 父进程执行
            close(pipefd[0]);
            channels.push_back(Channel(pipefd[1],id,cname));

            //让父进程此次创建的wfd保存,便于下次创建子进程继承时关闭之前的文件描述符
            fds.push_back(pipefd[1]);
        }
        return 0;
    }
    int NexChannel()
    {
        static int next=0;
        int c=next;
        next++;
        next%=channels.size();
        return c;
    }
    void SendTaskCode(int index,uint32_t code)
    {
        cout<<"send code: "<<code<<"to "<<channels[index].name()<<"sub process id: "<<channels[index].pid()<<endl;
        write(channels[index].wfd(),&code,sizeof(code));
    }

    //让所有子进程全部退出,只需要关闭所有的Channel w(写端)即可
    void KillAll()
    {
        for(auto &channel:channels)
        {
            channel.Close();
             pid_t pid=channel.pid();
            pid_t rid=waitpid(pid,nullptr,0);
            if(rid==pid)
            {
                cout<<"wait sub process: "<<pid<<" success..."<<endl;
            }
            cout<<channel.name()<<"close done"<<" sub process quit now: "<<channel.pid()<<endl;
            cout<<endl;
        }
    }
    void wait()
    {
        for(auto &channel:channels)
        {
            pid_t pid=channel.pid();
            pid_t rid=waitpid(pid,nullptr,0);
            if(rid==pid)
            {
                cout<<"wait sub process: "<<pid<<" success..."<<endl;
            }
        }
    }
    void Debug()
    {
        for(auto &channel:channels)
        {
            channel.PrintDebug();
        }
    }
    ~ProcessPool()
    {
    }
private:
    int _sub_process_num;
    vector<Channel> channels;
};

 2.2控制子进程

void CtrlProcessPool(ProcessPool* processpool_ptr,int cnt)
{
    while(cnt)
    {
        //a.选择一个进程和通道
        int channel=processpool_ptr->NexChannel();
        //b.选择一个任务
        uint32_t code=NextTask();
        //c.发送任务
        processpool_ptr->SendTaskCode(channel,code);

        sleep(1);
        cnt--;
    }
}

 2.3回收进程

 //让所有子进程全部退出,只需要关闭所有的Channel w(写端)即可
    void KillAll()
    {
        for(auto &channel:channels)
        {
            channel.Close();
            pid_t pid=channel.pid();
            pid_t rid=waitpid(pid,nullptr,0);
            if(rid==pid)
            {
                cout<<"wait sub process: "<<pid<<" success..."<<endl;
            }
            cout<<channel.name()<<"close done"<<" sub process quit now: "<<channel.pid()<<endl;
            cout<<endl;
        }
    }

三、task.hpp

在task.hpp中我们可以模拟一些我们需要执行的进程任务并对其进行封装处理,父进程负责通过向管道write向子进程发送需要执行的具体任务信息,子进程则通过read读到需要用到的进程和其需要执行的具体任务,前面的代码中我们已经把创建的子进程所对应的管道的读端重定向到0,所以worker在读取任务时直接从0中读取即可。

#pragma once
#include <iostream>
#include <unistd.h>

using namespace std;

typedef void(*work_t)(int);//函数指针类型
typedef void(*task_t)(int,pid_t);//函数指针类型

void PrintLog(int fd,pid_t pid)
{
    cout<<"sub process:"<<pid<<",fd: "<<fd<<",task is:printf log task"<<endl<<endl;
}

void ReloadConf(int fd,pid_t pid)
{
    cout<<"sub process:"<<pid<<",fd: "<<fd<<",task is:reload conf task"<<endl<<endl;
}

void ConnectMysql(int fd,pid_t pid)
{
    cout<<"sub process:"<<pid<<",fd: "<<fd<<",task is:connect mysql task"<<endl<<endl;
}

task_t task[3]={PrintLog,ReloadConf,ConnectMysql};

uint32_t NextTask()
{
    return rand()%3;
}

void worker(int fd)
{
    //从0中读取任务
    while(true)
    {
        uint32_t command_code=0;
        ssize_t n=read(0,&command_code,sizeof(command_code));
        if(n==sizeof(command_code))
        {
            if(command_code>=3) continue;
            task[command_code](fd,getpid());
        }
        else if(n==0)
        {
            cout<<"sub process: "<<getpid()<<" quit now.."<<endl;
            break;
        }
    }
}

 父进程可以随机的向特定管道写任务码,然后子进程再从各自相连接的管道中读取任务码,没有任务码时子进程就处于阻塞状态,有任务时就去读取并执行worker去执行我们提前构建好的任务列表中的特定任务。

 四、完整代码

#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <unistd.h>
#include <ctime>
#include <sys/wait.h>
#include "task.hpp"
using namespace std;
enum
{
    UsageError=1,
    ArgError,
    PipeError
};

void Usage(const string &proc)
{
    cout<<"Usage:"<<proc<<"subprocess-num"<<endl;
}


class Channel//保存管道的信息和写端fd
{
public:
    Channel(int wfd,pid_t sub_id,const string &name)
    :_wfd(wfd),_sub_process_id(sub_id),_name(name)
    {}
    void PrintDebug()
    {
        cout<<"_wfd:"<<_wfd;
        cout<<",_sub_process_id:"<<_sub_process_id;
        cout<<",_name:"<<_name<<endl;
    }
    string name(){return _name;}
    int wfd(){return _wfd;}
    pid_t pid(){return _sub_process_id;}
    void Close(){ close(_wfd); }
    ~Channel()
    {}
private:
    int _wfd;
    pid_t _sub_process_id;
    string _name;
};
//1.创建通信信道和子进程
class ProcessPool
{
public:
    ProcessPool(int sub_process_num):_sub_process_num(sub_process_num)
    {}
    int CreateProcess(work_t work)//回调函数
    {
        vector<int> fds;
        for(int number=0;number<_sub_process_num;number++)
        {
            int pipefd[2]{0};
            int n=pipe(pipefd);
            if(n<0) return PipeError;

            pid_t id=fork();
            //子进程执行关闭写端,去读
            if(id==0)
            {
                //把父进程历史打开的写端关闭
                if(!fds.empty())
                {
                    cout<<"close w_fd:";
                    for(auto fd:fds) 
                    {
                        close(fd);
                        cout<<fd<<" ";
                    }
                    cout<<endl;
                }
                //child -> r
                close(pipefd[1]);
                //执行任务

                //为什么要dup2重定向:
                //原本从标准输入中读,变成从管道中读,
                //也就是此时当前子进程fd0中存放的就是当前管道的地址
                //之后通过访问标准输入就可以读到管道中的内容。
                dup2(pipefd[0],0);
                work(pipefd[0]);
                exit(0);
            }

            string cname="channel-"+to_string(number);
            //father 父进程执行
            close(pipefd[0]);
            channels.push_back(Channel(pipefd[1],id,cname));

            //让父进程此次创建的wfd保存,便于下次创建子进程继承时关闭之前的文件描述符
            fds.push_back(pipefd[1]);
        }
        return 0;
    }
    int NexChannel()
    {
        static int next=0;
        int c=next;
        next++;
        next%=channels.size();
        return c;
    }
    void SendTaskCode(int index,uint32_t code)
    {
        cout<<"send code: "<<code<<"to "<<channels[index].name()<<"sub process id: "<<channels[index].pid()<<endl;
        write(channels[index].wfd(),&code,sizeof(code));
    }

    //让所有子进程全部退出,只需要关闭所有的Channel w(写端)即可
    void KillAll()
    {
        for(auto &channel:channels)
        {
            channel.Close();
            pid_t pid=channel.pid();
            pid_t rid=waitpid(pid,nullptr,0);
            if(rid==pid)
            {
                cout<<"wait sub process: "<<pid<<" success..."<<endl;
            }
            cout<<channel.name()<<"close done"<<" sub process quit now: "<<channel.pid()<<endl;
            cout<<endl;
        }
    }
    void wait()
    {
        for(auto &channel:channels)
        {
            pid_t pid=channel.pid();
            pid_t rid=waitpid(pid,nullptr,0);
            if(rid==pid)
            {
                cout<<"wait sub process: "<<pid<<" success..."<<endl;
            }
        }
    }
    void Debug()
    {
        for(auto &channel:channels)
        {
            channel.PrintDebug();
        }
    }
    ~ProcessPool()
    {
    }
private:
    int _sub_process_num;
    vector<Channel> channels;
};
void CtrlProcessPool(ProcessPool* processpool_ptr,int cnt)
{
    while(cnt)
    {
        //a.选择一个进程和通道
        int channel=processpool_ptr->NexChannel();
        //b.选择一个任务
        uint32_t code=NextTask();
        //c.发送任务
        processpool_ptr->SendTaskCode(channel,code);

        sleep(1);
        cnt--;
    }
}
int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        Usage(argv[0]);
        return UsageError;
    }
    int sub_process_num=stoi(argv[1]);
    if(sub_process_num<=0)
    return ArgError;
    srand((uint64_t)time(nullptr));

    //1.创建通信信道和子进程
    ProcessPool *processpool_ptr=new ProcessPool(sub_process_num);
    processpool_ptr->CreateProcess(worker);
    //2.控制子进程
    CtrlProcessPool(processpool_ptr,10);

    cout<<"task run done"<<endl;

    //3.回收进程
    processpool_ptr->KillAll();

    //防止僵尸出现,需要父进程对其进行资源回收
    //processpool_ptr->wait();

    
    delete processpool_ptr;

    return 0;
}

  • 30
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C+五条

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值