【问题标题】:fork a child process inside while loop在while循环中fork一个子进程
【发布时间】:2020-07-29 07:37:27
【问题描述】:

我对 unix sys 调用相当陌生,最近我遇到了一个问题,即对子进程有多个 fork() 调用。我对输出感到困惑。

int main() {
    int count = 0;
    int pid;
    if (!(pid = fork())) {

        while ((count < 2) && (pid = fork())) {
            count++;
            printf("Count for pid: %d: %d\n", getpid(), count);
        }
        if (count > 0) {
            printf("Count for pid: %d: %d\n", getpid(), count);
        }
    }
    if (pid) {
        printf("pid is %d, and we waitpid\n", pid);
        waitpid(pid, 0, 0);
        count = count << 1;
        printf("Count for pid: %d: %d\n", getpid(), count);
    }
}

我得到的输出是:

pid is 12933, and we waitpid
Count for pid: 12933: 1
Count for pid: 12933: 2
Count for pid: 12933: 2
pid is 12935, and we waitpid
Count for pid: 12935: 1
Count for pid: 12933: 4
Count for pid: 12932: 0

所以我的问题是,为什么只有 3 个唯一的 pid,while 循环中的 fork 不应该创建比 3 个更多的子进程吗?

【问题讨论】:

    标签: operating-system fork system-calls multiprocess


    【解决方案1】:

    你可能知道fork返回值:

    成功时,在父进程中返回子进程的PID, 并且在孩子中返回 0。失败时,-1 在 parent,没有创建子进程,并且设置了适当的errno。

    所以,你的代码会遍历这样一棵树:

    我已经为每个 'printf' 函数写了序列号。

    【讨论】:

      猜你喜欢
      • 2015-07-16
      • 2020-01-04
      • 2018-07-26
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 2015-11-08
      • 2014-08-06
      • 2012-10-28
      相关资源
      最近更新 更多