代码拉取完成,页面将自动刷新
#include"Task.hpp"
#include<string>
#include<vector>
#include<cassert>
#include<ctime>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
const int processNum = 10; //一次性创建5个子进程
std::vector<task_t> tasks;
class channel
{
public:
channel(int cmdFd, pid_t slaverId, const std::string &processName)
:_cmdFd(cmdFd)
,_slaverId(slaverId)
,_processName(processName)
{}
public:
int _cmdFd; //发送任务的文件名描述符
pid_t _slaverId; //子进程pid
std::string _processName; //子进程名字
};
void Slaver()
{
int cnt = 2;
while(true)
{
int cmdCode = 0;
int n = read(0, &cmdCode, sizeof(cmdCode));
if(n == sizeof(int))
{
std::cout << "slaver say@get a command:" << getpid() << " : cmdCode: " << cmdCode << std::endl;
if(cmdCode >= 0 && cmdCode < tasks.size()) tasks[cmdCode]();
}
if(n == 0) break;
}
}
void InitProcessPool(std::vector<channel> *channels)
{
std::vector<int> oldfds;
for(int i = 0; i < processNum; i++)
{
int pipefd[2] = {0};
//管道创建
int n = pipe(pipefd);
assert(!n);
(void)n;
pid_t id = fork();
if(id == 0)
{
//关闭上一个写端
for(auto e : oldfds) close(e);
//child 读端
close(pipefd[1]);
dup2(pipefd[0],0); //重定向,从管道里读
close(pipefd[0]);
Slaver();
exit(0);
}
//father 写端
close(pipefd[0]);
std::string name = "process -" + std::to_string(i);
//匿名对象
channels->push_back(channel(pipefd[1], id, name));
oldfds.push_back(pipefd[1]);
}
}
void Debug(const std::vector<channel> &channels)
{
for(const auto &e : channels)
{
std::cout << e._cmdFd << " " << e._processName.c_str() << " " << e._slaverId << std::endl;
}
}
void CtrlProcess(const std::vector<channel> &channels)
{
int cnt = 5;
while(cnt--)
{
//随机发布任务
int cmdCode = rand()%tasks.size();
//选择进程
int processPos = rand()%sizeof(channels.size());
std::cout << "father say@" << "command:" << cmdCode << " already sendto " << channels[processPos]._slaverId << " process name:"
<< channels[processPos]._cmdFd << std::endl;
//发送任务
write(channels[processPos]._cmdFd, &cmdCode, sizeof(cmdCode));
sleep(1);
}
}
void QuitProcess(const std::vector<channel> &channels)
{
//关闭文件描述符
for(const auto &e : channels)
{
close(e._cmdFd);
std::cout << e._cmdFd << " " << e._processName << " " << e._slaverId << std::endl;
sleep(1);
waitpid(e._slaverId, nullptr, 0);
}
}
int main()
{
LoadTask(&tasks);
srand(time(nullptr)^getpid()^1023);
//进程组织
std::vector<channel> channels;
//初始化--创建子进程、建立通信信道
InitProcessPool(&channels);
Debug(channels);
//控制子进程
CtrlProcess(channels);
//sleep(1000);
//清理收尾
QuitProcess(channels);
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。