You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言使用fork函数按输入深度宽度创建进程树的问题求助

C语言fork进程树实现修正

你现有代码的核心问题有两个:

  • 子进程完成自身的fork逻辑后没有主动退出,会继续执行外层父进程的代码逻辑,生成大量多余进程
  • 没有实现嵌套的层级结构:当前代码里每个一级子进程创建的是depth个平级子进程,并不是逐层向下的树形结构

修正后的代码如下,会按照输入的深度、宽度生成对应的层级进程树:

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

// 递归创建子进程的函数
void create_tree(int current_depth, int max_depth, int width) {
    // 达到最大深度就停止创建
    if (current_depth >= max_depth) {
        printf("层级%d 进程ID: %d 父进程ID: %d\n", current_depth, getpid(), getppid());
        sleep(1);
        exit(0);
    }
    // 循环创建width个子进程
    for (int i = 0; i < width; i++) {
        pid_t pid = fork();
        if (pid < 0) {
            perror("fork错误");
            exit(1);
        } else if (pid == 0) {
            // 子进程进入下一层级继续创建
            create_tree(current_depth + 1, max_depth, width);
        }
    }
    // 父进程等待所有子进程退出
    for (int i = 0; i < width; i++) {
        wait(NULL);
    }
    printf("层级%d 进程ID: %d 父进程ID: %d\n", current_depth, getpid(), getppid());
    sleep(1);
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("使用方法: %s <最大深度> <宽度>\n", argv[0]);
        exit(1);
    }
    int max_depth = atoi(argv[1]);
    int width = atoi(argv[2]);
    // 根节点从层级0开始创建
    create_tree(0, max_depth, width);
    return 0;
}

使用方法:

  • 编译代码:gcc process_tree.c -o process_tree
  • 运行示例(深度2,宽度2):./process_tree 2 2
    运行后会按层级打印所有进程的ID和父进程ID,可自行核对进程树结构是否符合要求。

内容的提问来源于stack exchange,提问作者user260563

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:15:00