一尘不染

如何等待直到fork()调用的所有子进程完成?

linux

我分叉了多个流程,我想衡量完成整个任务需要多长时间,即所有分叉的流程都完成了。请告知如何使父进程等待所有子进程终止?我想确保在正确的时间停止计时器。

这是我使用的代码:

#include <iostream>
#include <string>
#include <fstream>
#include <sys/time.h>
#include <sys/wait.h>

using namespace std;

struct timeval first,  second,  lapsed;
struct timezone tzp;

int main(int argc, char* argv[])// query, file, num. of processes.
{

    int pCount = 5; // process count

    gettimeofday (&first, &tzp); //start time

    pid_t* pID = new pid_t[pCount];

    for(int indexOfProcess=0; indexOfProcess<pCount; indexOfProcess++)
    {
        pID[indexOfProcess]= fork();

        if (pID[indexOfProcess] == 0)                // child
        {
            // code only executed by child process

            // magic here

            // The End
            exit(0);
        }
        else if (pID[indexOfProcess] < 0)    // failed to fork
        {
            cerr << "Failed to fork" << endl;
            exit(1);
        }
        else                         // parent
        {
            // if(indexOfProcess==pCount-1) and a loop with waitpid??

            gettimeofday (&second, &tzp); //stop time
            if (first.tv_usec > second.tv_usec)
            {
                second.tv_usec += 1000000;
                second.tv_sec--;
            }

            lapsed.tv_usec = second.tv_usec - first.tv_usec;
            lapsed.tv_sec = second.tv_sec - first.tv_sec;

            cout << "Job performed in " <<lapsed.tv_sec << " sec and " << lapsed.tv_usec    << " usec"<< endl << endl;

        }

    }//for

}//main

阅读 532

收藏
2020-06-03

共1个答案

一尘不染

我将在“ else //
parent”行之后的所有内容都移到for循环之外。在分叉循环之后,使用waitpid进行另一个for循环,然后停止计时并执行其余操作:

for (int i = 0; i < pidCount; ++i) {
    int status;
    while (-1 == waitpid(pids[i], &status, 0));
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
        cerr << "Process " << i << " (pid " << pids[i] << ") failed" << endl;
        exit(1);
    }
}

gettimeofday (&second, &tzp); //stop time

我假设如果子进程无法正常退出且状态为0,则它​​没有完成其工作,因此测试未能生成有效的计时数据。显然,如果子进程 应该
被信号杀死,或者退出非零返回状态,则必须相应地更改错误检查。

使用等待的替代方法:

while (true) {
    int status;
    pid_t done = wait(&status);
    if (done == -1) {
        if (errno == ECHILD) break; // no more child processes
    } else {
        if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
            cerr << "pid " << done << " failed" << endl;
            exit(1);
        }
    }
}

这个不会告诉您顺序中哪个进程失败,但是如果您愿意,可以添加代码以在pids数组中查找并获取索引。

2020-06-03