【发布时间】:2017-02-14 01:49:25
【问题描述】:
我正在我的 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),另外 1 个来自 3 个生成的子级中的每个。相反,我收到的是:
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 时打印两次,i==3 时打印一次)。
为什么会发生这种情况?为什么我没有收到来自父母的 3 张打印件(当 i==1、i==2、i==3 时一次)。如果我们从父级的角度来看 - 有一个 while 循环,我们应该只在里面点击 print 语句 3 次。
也许那个 fork 是异步的还是什么?我错过了什么?
【问题讨论】:
标签: c multiprocessing fork