我正在编写一个旨在固定 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/