gpt4 book ai didi

c - 调用 fork() 后打印出的额外数据

转载 作者:行者123 更新时间:2023-12-02 06:14:48 25 4
gpt4 key购买 nike

<分区>

我正在我的 Mac 上运行我用 c 编写的以下代码。

#include <unistd.h>
#include <stdio.h>

int main(int argc, const char * argv[]) {

int i = 0;
printf("Starting pid:%d\n", getpid());
while(i++<3){
int ret = fork();
printf("hello(%d)%d, %d ", i, getpid(), ret);
if(!ret){
printf("\n");
return 0;}
}
}

我的目标是总共有 6 个打印 - 3 个来自原始父级(打印在“起始 pid”中的 pid),另外 3 个衍生子级各有 1 个。相反,我收到的是:

Starting pid:7998
hello(1)8009, 0
hello(1)7998, 8009 hello(2)8010, 0
hello(1)7998, 8009 hello(2)7998, 8010 hello(3)7998, 8011 hello(1)7998, 8009 hello(2)7998, 8010 hello(3)8011, 0

请注意,原始父级 (7998) 打印了 6 次(i==1 时打印 3 次,i==2 时打印 2 次,i==3 时打印 1 次)。

为什么会这样?为什么我没有收到来自 parent 的 3 份打印件(一次是 i==1,i==2,i==3)。如果我们从父级的角度来看 - 有一个 while 循环,我们应该只在内部打印 3 次语句。

fork 可能是异步的还是什么?我错过了什么?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com