For循环中的fork() [英] fork() in a For Loop

查看:210
本文介绍了For循环中的fork()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <sys/type.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.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");
        }
    }

    if(pid != 0) {
        while((pid = waitpid(-1, NULL, 0)) > 0)
            if(errno == ECHILD)
                break;
            printf("I am parent and all children have exited.\n");
    }
    exit(0);

    return 0;
}

结果是,

我是孩子"被印刷了7次, 我是父母,所有孩子都退出了."被打印了四次

'I am child' is printed 7 times, 'I am parent and all children have exited.' is printed 4 times

并且打印顺序不固定.

这是我的问题!

为什么我是孩子"被打印7次,

Why 'I am child' is printed 7 times,

和我是父母,所有孩子都退出了."被打印了4次?

and 'I am parent and all children have exited.' is printed 4 times ?

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

I don't understand the number of times those sentences are printed.

您能详细解释一下吗?

推荐答案

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

You can try the code below. You need to add the wait header. At the same time, after providing the 0 condition of the child processes, you should definitely sign out, otherwise each processes will fork again and again each time in the code. Shortly you have to kill every process after their task end.

#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;
}

这篇关于For循环中的fork()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆