【发布时间】: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