c - C 中的进程树层次结构

标签 c process tree

我正在尝试创建一个进程树层次结构,为树的高度 H 创建 C 个子进程。我编写了以下代码,但每个进程只创建一个子进程。我哪里错了?

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

void createProcess(int height,int children){
    int root, parent, t1, t2, t3, i, pid, status; 

    root = getpid();
    parent = getppid();
    printf("%d: Process starting\n", root);
    printf("%d: Parent's id = %d\n", root, parent);
    printf("%d: Height in the tree = %d\n", root, height);
    printf("%d: Creating %d children at height %d\n", root, children, height - 1);

    char c[4], h[4];
    sprintf(h, "%d", height - 1);
    sprintf(c, "%d", children);

    char *args[] = {"./forkk", h, c, NULL}; 
    for (i = 0; i < children; i++) {
        t1 = fork();
        if (t1 != 0) {
            printf("child pid %d    parent pid %d\n", getpid(), getppid());
            break;
        }
        if (t1 == 0) {
            execvp("./forkk", args);
        }
    }
    pid = wait(&status);
    sleep(5);
    //printf("%d Terminating at Height %d\n",root,height);
}

int main(int argc, char** argv) {
    int i;

    printf("No of Arguments: %d\n", argc);
    for (i = 0; i < argc; i++) {
        printf("%s\n", argv[i]);
    }
    int height = atoi(argv[1]);
    int children = atoi(argv[2]);
    printf("Height  %d\n", height);
    printf("Children  %d\n", children);
    if (height > 1)
        createProcess(height, children);
    return 0;
}

最佳答案

这是因为在 for 循环中有 break。在 if (t1 != 0) 中。父级在创建第一个子级后退出循环。

@John Bollinger 是对的,这样做很糟糕。您正在做的是递归调用 main 函数。您应该并且可以在 createProcess 中处理这个问题。

关于c - C 中的进程树层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52156763/

相关文章:

c - C中有调节背景颜色的函数吗? (实际上是一个Dos命令)

c# - 打开没有 Process.start 的网站

java - 需要显示一个可以动态(无限)添加到(java)的树状结构?

json - Treestore 为空 - JSON 有效吗?

c - 使用 memcpy 进行内联线程调度

c - 在 C 中读取 csv 文件,strtok 没有返回我所期望的?

c - 在链接列表中使用 "void *"时出现问题

windows - Windows 应用程序如何使用多个进程?

google-chrome-extension - 是否有从 chrome 扩展获取桌面事件应用程序名称的解决方案?

algorithm - 树的深度和高度有什么区别?