c - 父进程不等待子进程 - C

标签 c linux multiprocessing wait

我正在编写一个旨在固定 CPU 使用率的程序,我将其用作衡量性能的工具。该程序相当简单,因为它从父进程派生了 5 个子进程。下面是我的代码片段

int main(int argc, char **argv) {
  pid_t pid = 0; 
  int i;

  for(i = 0; i < 5; i++)
    //create 5 additional processes
    if((pid = fork()) == 0) {
        //do CPU intensive task
      break;
    }

  //fork error 
  if(pid == -1) {
    perror("<fork failed>\n");
    return EXIT_FAILURE;
  }

  //if parent
  if(pid != 0)
    //wait for children to finish
    wait(NULL);

  return EXIT_SUCCESS;
}

然而,尽管有 wait(NULL) 函数,父进程会立即退出。任何关于为什么会发生这种情况以及如何解决它的想法将不胜感激。

最佳答案

您正在创建五个 child ,但是 wait 会在其中任何一个退出时立即返回。你想等待所有这些,所以你需要重复调​​用 wait。当您没有 child 时,wait 函数返回 -1 并将 errno 设置为 ECHILD:

while (wait(NULL) != -1 || errno != ECHILD) {
    // nothing
}

关于c - 父进程不等待子进程 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324391/

相关文章:

c - OpenMP 并行乘法比顺序乘法慢

linux - 如何只提取 ELF 部分的原始内容?

r - 在 clusterApply 或 clusterMap 中将进度打印到 windows cmd

c - sscanf 在大数上出现段错误

编译器行为?

python - 如果我在 Ubuntu 上开始学习 C,它会在我今年夏天晚些时候开始学习 Objective-C 时给我带来优势吗?

linux - 系统调用何时以及如何中断?

python - Multiprocessing.pool 具有多个 args 和 kwargs 的函数

c++ - 多线程 (openMP) - 有多少并行线程

c - 为什么fork后关闭文件描述符会影响子进程?