我将在“ 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数组中查找并获取索引。



