Can a child process wait for it's sibling proc

2019-07-16 07:04发布

问题:

I'm trying to get from a child process the exit status of its 'sibling',

I've tried to do that:

int main(void){
    int i,j,status,p1;
    pid_t pids[2],pid;
    for (i = 0; i < 2; i++){
        pids[i]=fork();
    /*child 1*/
        if(pids[i]==0 && i==0)exit(5);
    /*child 2*/
        else if(pids[i]==0 && i==1){
            waitpid(pids[0],&p1,0);
            exit(WEXITSTATUS(p1));
        }
    }

    for(j=0;j<2;j++ ){
        pid = wait(&status);
        if(pid==pids[0]){
            printf("child process 0 exit with status %d\n",WEXITSTATUS(status));
        }
        else if(pid==pids[1]){
            printf("child process 1 exit with status %d\n",WEXITSTATUS(status));
        }
    }
    return 0;
}

But the output I get is:

child process 0 exit with status 5
child process 1 exit with status 0

Is there a way to do that?

回答1:

No. You can only wait() on a process that you created.



标签: c process fork