c - 子进程的递归命令

标签 c recursion tree fork wait

我的代码:

int i, pid;

int mainPid = getpid();

for(i = 0; i < atoi(argv[1]); i++) {
    pid = fork();
    if(pid < 0) {
        printf("Error");
        exit(1);
    } else if (pid == 0) {
        printf("Child (%d): %d\n", i + 1, getpid());
        sleep(1);
        //SOME RECURSIVE FUNCTION FOR CHILD
        exit(0); 
    }
}


if(fork() == 0) {

    char a[100];
    sprintf(a, "%d", mainPid);
    execlp("pstree", "pstree", "-c", a, NULL);

}else { 
    sleep(1); 
}    

当参数为8时我得到的输出是:

Child (2): 3031
Child (7): 3036
Child (6): 3035
Child (1): 3030
Child (5): 3034
Child (8): 3037
Child (4): 3033
Child (3): 3032
t1─┬─pstree
   ├─t1
   ├─t1
   ├─t1
   ├─t1
   ├─t1
   ├─t1
   ├─t1
   └─t1

很明显, child 并不是按数字顺序排列的,因为有些 child 先于其他 child 出生。

所以我的问题是,有没有办法强制按数字顺序,因为我想调用某种递归函数,该函数会从标准输入中读取数字,并从第一个子进程中生成许多子进程,然后读取来自标准输入的另一个数字,并从第二个 child 中产生了许多 child 等等......基本上最后,我想通过从主进程调用 pstree 来得到类似的东西:

   t1─┬─pstree
      ├─t1┬─t1
      |   └─t1
      ├─t1┬─t1─t1
      |   └─t1
      ├─t1
      ├─t1
      ├─t1─t1 
      └─t1

最佳答案

这是一个相当老的问题,但我仍然认为很好回答:

我稍微调整了您的打印语句,如下

for(i = 0; i < atoi(argv[1]); i++) {
    pid = fork();
    if(pid < 0) {
        printf("Error");
        exit(1);
    } else if (pid == 0) {
        //printf("Child (%d): %d\n", i + 1, getpid());
        sleep(1);
        //SOME RECURSIVE FUNCTION FOR CHILD
        exit(0);
    } else {
        printf("Child (%d): %d\n", i + 1, pid);
    }
}

if(!(fork() == 0)) {

    char a[100];
    sprintf(a, "%d", mainPid);
    execlp("pstree", "pstree", "-c", a, NULL);

}else {
    sleep(1);
}

我得到了你所期望的(我相信):

Child (1): 10238
Child (2): 10239
Child (3): 10240
Child (4): 10241
Child (5): 10242
Child (6): 10243
Child (7): 10244
Child (8): 10245
pstree─┬─a.out
       ├─a.out
       ├─a.out
       ├─a.out
       ├─a.out
       ├─a.out
       ├─a.out
       ├─a.out
       └─a.out

如果这不是您所期望的,请告诉我。另外,如果你已经修复了它,如何修复? :)

关于c - 子进程的递归命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27696529/

相关文章:

C 字符串、strlen 和 Valgrind

JavaScript 递归验证

algorithm - 想要 : Theory for Copy, 在树中的节点中 move (例如拖放)

javascript - 如何递归更改元素的颜色

javascript - 修复: JS recursive function to get the nested (multilevel) child objects as array of objects

C++ - 解决数独游戏

java - 递归调用占用内存

为 goto 函数创建外部标签以跨源文件工作

c - C 中强制转换指针的含义

java - 错误 : conflicting types for JNI method