【问题标题】:Process Tree Hierarchy in CC中的进程树层次结构
【发布时间】:2018-09-03 22:29:45
【问题描述】:

我正在尝试创建一个进程树层次结构,该层次结构为树高 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;
}

【问题讨论】:

  • 每个孩子都需要execvp()(我假设)相同的程序吗?这样做本身并没有错,但它确实使事情复杂化了,没有明显的原因..
  • @JohnBollinger 要求子进程再次调用main

标签: c process tree


【解决方案1】:

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

@John Bollinger 是对的,这是一种糟糕的做法。你正在做的是递归调用main 函数。你应该也可以在createProcess 处理这个问题。

【讨论】:

  • 是的,你是对的,break 函数导致循环停止。并且需要递归调用main函数。谢谢:)
  • @DipeshDesai 然后可以直接调用main函数,而不是调用execmain 与其他功能没有什么不同。如果您也必须使用 exec,则应使用 argv[0] 作为程序名称,而不是字符串文字。如果您的可执行文件未命名为 forkk,这将不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多