c - 父进程如何等待所有子进程终止

标签 c

<分区>

我是 C 的新手,所以我只知道简单的函数。(例如:wait(NULL))。

这是我的主要问题:

Modify the program so that only the parent process creates 3 child processes, and each new created process calls a function CPU(). In addition, make the parent process wait for each child’s termination.

我知道这个是正确答案

#include<stdio.h>

int main(void)
{
    int i ;

    for( i = 0; i < 3; i++)
    {
        int ret = fork();
        if(ret == 0){
            printf("My process ID is %d\n", getpid());
            return 0;
        }

    }

    for (i = 0; i < 3; i++) //Line B
        wait(NULL);
}

但我的问题是

  1. 为什么wait在循环中被parent执行时下面的代码是错误的

    #include <stdio.h>
    
    int main(void)
    {
        int i ;
    
        for( i = 0; i < 3; i++)
        {
            int ret = fork();
    
            if(ret == 0) {
                printf("My process ID is %d\n", getpid());
                return 0;
            }
            else
                wait(NULL);
        }
    }
    
  2. 在最开始的代码中,为什么我们要在 for 循环中编写 wait(NULL)? 我们不能不使用 for 循环来写吗

  3. 如果子进程中没有“return 0”,for循环是否应该改为

    for (i = 0; i <7; i++)
        wait(NULL);
    
  4. 我不会写CPU函数

最佳答案

  1. 此代码不会并行执行子进程,而是按顺序执行每个子进程。 直到子进程执行除了打印一条消息并退出之外的操作(您可以添加 sleep(1) )时,差异才会显示出来。

  2. wait函数将等待终止一个 子进程(以先完成者为准)。如果你有 3 个子进程,你必须调用 wait至少成功 3 次以确保它们中的每一个都已终止。也许更容易调用 wait直到设置 errnoECHILD , 意思是没有 child 了:

    while (1) {
        errno = 0;
        if (wait(NULL) == -1) {
            if (errno != ECHILD) {
                perror("Unexpected error from wait");
            }
            break;
        }       
    }
    
  3. 每个父进程都应等待其自己的子进程 ( or set the SIGCHLD disposition to SIG_IGN )。而不是计算 wait 的数量s,使用上面的代码

  4. 这意味着:“通过名称 CPU 调用一个函数”,即

    void CPU(void) {
    }
    

    在子进程中。


顺便说一句,您的代码缺少几个函数的必要 header -

#include <sys/types.h>
#include <sys/wait.h>

wait ,

#include <unistd.h>

fork另外#include <errno.h>对于我的 errno添加。

关于c - 父进程如何等待所有子进程终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50207205/

相关文章:

c - 用逗号分隔符和 sscanf 分隔的整数

c - 如何对字符数组(字符串)使用 isdisit()?

c - 使用 "while"检查是否有空行C

c - 用 C 编写一个程序,该程序将采用一个基数和 n 位数字,并输出由这些数字表示的十进制数

c - gdb 耗时太长,Ctrl-C 无效

通过 stdin 检查文件是否存在 (C)

c - 在通过 execv 执行的子进程中使用 Scanf() 不起作用

c - Makefile 的详细信息

c - 如何创建结构体并通过 pthread_create() 传递给新线程

C - 数组超出范围