【发布时间】:2021-05-30 05:00:28
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include<sys/wait.h>
int main(){
int num = 2;
if (!fork()){
num++;
printf ("First: num = %d\n", num);
}else{
wait(NULL);
if (!fork()){
num++;
printf ("Second: num = %d\n", num);
}else{
wait(NULL);
num++;
printf ("Third: num = %d\n", num);
fflush(stdout);
exit(0);
}
}
fflush(stdout);
}
有人可以解释为什么 num 最终是 3 吗?我在 fork() 上找不到很好的解释。 (!fork()) 甚至有什么作用??
【问题讨论】:
-
'我找不到关于 fork() 的好解释。 (!fork()) 甚至做了什么?? - 我发现这些陈述/问题与可以通过参考印刷文献和搜索引擎检索到的在线资源来验证和证明的事实之间没有相关性。
-
OT:函数
fork()有三种返回值1)>0表示在父进程中。 2) =0 表示在子进程中。 3) -
建议阅读:fork。顺便说一句:如果你不知道
fork()的作用,你为什么还要使用它? -
@user3629249:OP 没有使用
fork。这是他们正在检查的代码,而不是他们正在编写的代码。
标签: c operating-system fork