简体   繁体   English

fork()两个子进程

[英]fork() two child process in c

ac program that forks 2 child,first one sleeps for 10 sec,the second one waits for the exit of the first child and prints a related message,the parent waits for the termination of the 2 child,i do not know why the second child does not wait for the 1st child termination.plz help 一个分叉2个孩子的ac程序,第一个孩子睡觉10秒钟,第二个孩子等待第一个孩子退出并打印相关消息,父级等待第2个孩子终止,我不知道为什么第二个孩子不等待第一个子终止.plz帮助

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

main(){
    int status;
        pid_t child1, child2,ret,ret2;

    child1=fork();
    if(child1==0){
        //this branch of code is being executed by the child1 process

        printf("I'm the first child with %d, I sleep for 10 sec \n",getpid());
        sleep(10);
        printf("child1 pid %d exiting\n",getpid());
                exit(1);
    }
    if(child1>0){

        child2=fork();
        ret=waitpid(child1,&status,0);


        if(child2==0){

             wait(&status);//???why child2 does not wait the child1 exit?

            printf("I'm the second child with %d, I have waited for the termination of the first child\n",getpid());
                        printf("child2 exited\n");
                        exit(1);

        }
        if(child2>0){


                        printf("father of child2 is waiting\n");
            ret2=waitpid(child2,&status,0);
            printf("I'm the father, my terminated process id is: %d \n",getpid());
            printf("I'm the father, my first child's id is: %d\n", child1);
            printf("I'm tha father, my second child's id is: %d\n", child2);

        }


    }

return 0;
}

The wait family of functions can only be used by parent to wait for a child. wait功能族只能由父母用来等待孩子。 They can't be used by a process to wait for a sibling. 进程无法使用它们来等待同级。

A process can only wait for its immediate children. 一个进程只能wait其直接子进程。 In this case, that means the parent process has to do the wait for both child1 and child2. 在这种情况下,这意味着父进程必须同时wait child1和child2。

In process hierarchy children doesn't wait neither for parent nor for another children. 在流程层次结构中,子级既不等待父级也不等待另一个子级。 You can use some form of IPC mechanism to communicate the info from 1 child to another, 您可以使用某种形式的IPC机制将信息从一个孩子传达给另一个孩子,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM