For循环中的fork()

问题描述 投票:-3回答:1
#include <stdio.h>
#include <sys/type.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>


















enter code here

enter image description here

结果是,

'我是孩子'被印刷了7次,“我是父母,所有孩子都退出了。”被打印4次

并且打印顺序不固定。

这是我的问题!

为什么“我是孩子”被打印了7次,

“我是父母,所有孩子都退出了。”被打印4次?

我不知道这些句子的打印次数。

您能详细解释吗?

c process fork parent
1个回答
0
投票

您可以尝试以下代码。您需要添加等待标头。同时,在提供子进程的0条件后,您一定要注销,否则每个进程都会在代码中一次又一次地派生。不久,您必须在任务结束后终止所有进程。

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>

int main(void){

    pid_t pid;
    int i;

    for (i = 0; i < 3; i++)
    {
        pid = fork();

        if (pid == -1) {

            printf("Fork Error.\n");

        } else if (pid == 0) {
            printf("I am child\n");
            exit(0); // !
        }
    }

    if (pid != 0) {

        while ((pid = waitpid(-1, NULL, 0)) > 0)
            if (errno == ECHILD)
                break;

        printf("I am parent and all children have exited.\n");
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.