首页 > 解决方案 > fork 命令创建进程树,无法显示 ppids

问题描述

我正在尝试创建一个进程树,如下所示: F \ |\1 \ | |\3 | \4 \2 F 和 1 将等待他们的孩子被终止。不知何故,所有的父母 pid 都被表示为 1。其次,我认为是“所有人的父亲”的过程 - F 似乎不是真正的父亲。这是我的代码:

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

int main (){
    int status;

    pid_t child_1;

    child_1 = fork();

    if(child_1 == 0){ //This is the child 1 process.
        printf("child 1:%d, %d\n", getpid());

        int returnStatus;
        waitpid(child_1, &returnStatus, 0);

        pid_t child_3 = fork();

        if(child_3 == 0){ //This is the child 3 process.
            printf("child 3:%d, %d\n", getpid());
            printf("parent child 3:%d\n", getppid());

        }

        else if(child_3 > 0){ // This is the father of child 3.

            pid_t child_4 = fork();

            if(child_4 == 0){ //This is the child 4 process.
                printf("child 4:%d, %d\n", getpid());
                printf("parent child 4:%d\n", getppid());

            }

        }
    }

    else { // This is the father of all processes.

        int returnStatus;
        waitpid(child_1, &returnStatus, 0);

        printf("FATHER OF THEM ALL:%d\n", getpid());

        pid_t child_2 = fork();

        if(child_2 == 0){ // This is the child 2 process.
            printf("child 2:%d, %d\n", getpid());

        }
    }

    return 0;
}

标签: ctreefork

解决方案


建议类似于以下的布局:

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

int main ( void )
{
    pid_t pid1 = fork();
    switch( pid1 )
    {
        case -1:
            perror( "fork for child1 failed" );
            exit( EXIT_FAILURE );
            break; 

        case 0:
            printf( "child1 pid: %d\n", getpid() );
            pid_t pid2 = fork();
            switch( pid2 )
            {
                case -1:
                    perror( "fork for child2 failed" );
                    exit( EXIT_FAILURE );
                    break;

                case 0:
                    printf( "child2 pid: %d\n", getpid() ); 
                    exit( EXIT_SUCCESS );
                    break;

                default: // in child 1
                { // braces so can have data declaration
                    int status2; 
                    waitpid( pid2, &status2, 0 );
                    exit( EXIT_SUCCESS );
                    break;
                }
            }
            break;

         default: // in original parent
         {
             int status1;
             waitpid( pid1, &status1, 0 );
         }
    }


    return 0;
}

正确处理child1和child2。在defaultchild1 的情况下,可以插入 child 1 的第 3 个和第 4 个子进程的代码


推荐阅读