1.一个父进程生成五个子进程且分别建立与子进程管道
①用for循环,结束条件为<5 ②father父进程每次都要离开for循环,生成下一个子进程和管道
2.#include
assert.h
是 C 标准库的头文件,cassert
是 C++ 标准库的头文件
3.子进程进行读取
那咱就关闭写端:close(pipefd[1]),保留读端
4.父进程进行写入
那咱就关闭读端:close(pipefd[0]),保留写端
5.让父进程实现:选择让哪个进程执行哪个命令
使用pair
vector
slots.push_back(pair
6.让子进程等待命令
waitCommand(pipefd[0]);//如果对方不发,我们就阻塞
int waitCommand(int waitFd)
{
uint32_t command = 0;
ssize_t s=read(waitFd,&command,sizeof(command));
assert(s == sizeof(uint32_t));
return command;
}
7.uint32_t对应几个字节
4个
8.typedef function
typedef function
代码实现:
Makefile:
ProcessPool:ProcessPool.cc
g++ -o $@ $^ -std=c++11 #-DDEBUG
.PHONY:clean
clean:
rm -f ProcessPool
Task.hpp
#pragma once
#include
#include
#include
#include
#include
#include
using namespace std;
typedef function func;//等价于 using func=function
vector callbacks;
unordered_map desc;
void readMySQL()
{
cout<<"process["<
processPool.cc
#include
#include
#include
#include
#include
#include
#include
#include "Task.hpp"
#include
#include
#define PROCESS_NUM 5
using namespace std;
int waitCommand(int waitFd,bool &quit)
{
uint32_t command = 0;
ssize_t s = read(waitFd, &command, sizeof(command));
if(s == 0)
{
quit=true;
return -1;
}
assert(s == sizeof(uint32_t));
return command;
}
void sendAndWakeup(pid_t who, int fd, uint32_t command)
{
write(fd,&command,sizeof(command));
cout<<"call process"<> slots;
// 先创建多个进程
for (int i = 0; i < PROCESS_NUM; i++)
{
// 创建管道
int pipefd[2] = {0};
int n = pipe(pipefd);
assert(n > 0);
(void)n;
pid_t id = fork();
assert(id != -1);
// 子进程我们让它进行读取
if (id == 0)
{
// 关闭写端
close(pipefd[1]);
// child
while (true)
{
// pipefd[0]
// 等命令
bool quit=false;
int command = waitCommand(pipefd[0],quit); // 如果对方不发,我们就阻塞
if(quit) break;
// 执行对应的命令
if (command >= 0 && command < handlerSize())
{
callbacks[command]();
}
else
{
cout << "非法command:" << command << endl;
}
}
exit(1);
}
// father,进行写入,关闭读端
close(pipefd[0]);
slots.push_back(pair(id, pipefd[1]));
}
// 父进程派发任务
srand(unsigned long)time(nullptr)^getpid()^23323123123L);//让数据更随机
while (true)
{
int select;
int command;
cout << "##############################################" << endl;
cout << "# 1.show functions 2.send command #" << endl;
cout << "##############################################" << endl;
cout << "Please Select>";
cin >> select;
if (select == 1)
showHandler();
else if (select == 2)
{
cout << "Enter Your Command>";
// 选择任务
cin >> command;
// 选择进程
int choice = rand() % slots.size();
// 把任务给指定的进程
sendAndWakeup(slots[choice].first, slots[choice].second, command);
}
}
// 关闭fd,所有的子进程都会退出
for(const auto& slot:slots)
{
close(slot.second);
}
//回收所有的子进程信息
for(const auto & slot:slots)
{
waitpid(slot.first,nullptr,0);
}
}