【问题标题】:recursive commands for process children子进程的递归命令
【发布时间】:2014-12-29 21:46:46
【问题描述】:

我的代码:

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

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

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

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

【问题讨论】:

  • 除非您以某种方式安排孩子们自己同步,否则您无法可靠地控制调度。
  • 他们井井有条! pid随着孩子单调增加。如果您想同步从标准输入读取的子级,最好的办法是让父级完成所有读取并将数据通过管道传递给子级。
  • 在此行之前:'for(i = 0; i 0,以确保参数为正数

标签: c recursion tree fork wait


【解决方案1】:

这是一个很老的问题,但我还是觉得很好回答:

我稍微调整了您的打印声明如下

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

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

【讨论】:

    猜你喜欢
    • 2017-03-23
    • 2011-11-05
    • 1970-01-01
    • 2021-05-23
    • 2014-06-13
    • 2020-02-19
    • 2014-03-26
    • 2021-04-13
    • 2021-09-17
    相关资源
    最近更新 更多