首页 > 解决方案 > 具有不同节点的 C (Linux) 中的叉树

问题描述

我在学校学习 C 和 Linux。我的任务是创建看起来像屏幕截图的家庭流程。

[![叉树][1]][1] [1]:https://i.stack.imgur.com/IV5zD.png

我不允许使用 break. 我在第一行使用了一个 for 循环 int i = 4 ,因此父级创建了 4 个子级。我尝试做另一个 for 循环 j < 2 ,以便 4 个孩子中的每一个创建 2 个孩子,但是循环创建了太多的孩子,父母不正确......我也尝试过 pid=fork(),它只创建了 1 个孩子。

你有一个想法,如何到 fork() 第二行,所以 4 个孩子每个创造 2 个孩子?我目前的代码是这样的:

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

int main() {
    int i,j;
    pid_t pid1,pid2;

    printf("Parent PID: %d\n", getpid());

    for (i = 0; i < 4; i++) {
        pid1 = fork();

        if (pid1 == -1) {
            perror("fork() failure");
            return 1;
        } else if (pid1 == 0) {
            printf("Child: PID: %d; PPID: %d\n", getpid(), getppid());
            pid2=fork();
                if(pid2==0){
                    printf("PID: %d of %d\n", getpid(), getppid());
                }
            return 0;
        }
    }
}

输出:

Parent PID: 1262
Child: PID: 1263; PPID: 1262
Child: PID: 1264; PPID: 1262
PID: 1265 of 1263
Child: PID: 1266; PPID: 1262
PID: 1267 of 1264
Child: PID: 1268; PPID: 1262
PID: 1269 of 1266
PID: 1270 of 1268

标签: clinuxprocesstreefork

解决方案


推荐阅读