使用带有多个子进程的execl

 ouyan1985_998 发布于 2023-01-19 10:12

我正在尝试创建一个创建多个子进程的进程,每个进程都调用该file()函数.

这是我到目前为止:

父级将文件列表写入管道

子进程将管道重定向到stdin并将stdout重定向到另一个管道和每个管道exec file.

父级使用select相关管道(包含文件功能的输出)等待子进程的终止并从中读取.

当我只使用一个子进程时,一切都运行良好:子进程终止管道中的所有输出,并且父进程读取它.但是,当我使用2个子进程时,它们不会终止; 文件功能进入"休眠"模式,等待更多输入.然后父母也被阻止,等待孩子们终止.

我已经创建了两个管道版本的最小包含示例:

#define NUM_CHILDREN (2)
//pipes from parent to children
int pipeP2C[NUM_CHILDREN][2];
//pipes from children to parent
int pipeC2P[NUM_CHILDREN][2];

int children_ids[NUM_CHILDREN];

int main()
{
//create pipes from parent to children and vice versa
for (int i = 0; i < NUM_CHILDREN; ++i){
    pipe(pipeP2C[i]);
    pipe(pipeC2P[i]);
}

//create first child
//Create initial g_parLevel child processes
pid_t pid;
int numForks = 0;
do
{
    pid = fork();
    // Parent process should count how many children it has
    if (pid > 0) {
        children_ids[numForks] = pid;
        ++numForks;
    }
    //child process also writes its' own pid to children_ids.
    else {
        children_ids[numForks] = (int)getpid();
    }
}
//Call fork again from parent process, if it doesn't have g_parLevel children already.
while (pid > 0 && numForks < NUM_CHILDREN);

//Now we have NUM_CHILDREN child processes, their ids are kept in the parent process, and each
//of them has (at least) it's own id kept in the suitable index in children_ids.

//parent - write to the children
if (pid > 0){
    //Iterate over all children
    for (int i = 0; i < NUM_CHILDREN; ++i)
    {
        std::string str = "/bin/ls";
        //close reading end
        close(pipeP2C[i][0]);
        //write to child
        write(pipeP2C[i][1], str.c_str(), (int)str.length());
        close(pipeP2C[i][1]);
    }

    //wait for the children to terminate
    int terminatedChildren = 0;
    while (terminatedChildren < NUM_CHILDREN)
    {
        int status;
        int terminatedChild = wait(&status);
        ++terminatedChildren;

        //read from the terminated child
        int childIndex = children_ids[0] == terminatedChild ? 0 : 1;

        //close writing end
        close(pipeC2P[childIndex][1]);
        char buf[2048];
        read(pipeC2P[childIndex][0], buf, sizeof(buf));
        close(pipeC2P[childIndex][0]);
        std::cerr<<"output from child "< 0){
            std::cerr<<"ready"<

为什么不等

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有