在fork()程序中首先执行什么?父母还是孩子?

时间:2013-06-30 08:36:45

标签: c unix fork

我不知道fork中首先执行了什么。例如,我有这段代码:

int main() {
   int n = 1;
   if(fork() == 0) {
      n = n + 1;
      exit(0);
   }
   n = n + 2;
   printf(“%d: %d\n”, getpid(), n);
   wait(0);
   return 0;
}

这会在屏幕上打印什么?

1: 3
0: 4

0: 4
1: 3

3 个答案:

答案 0 :(得分:4)

未指定。操作系统调度程序决定首先安排哪个进程。

After a fork(), it is indeterminate which process—the parent
or the child—next has access to the CPU. On a multiprocessor system,
they may both simultaneously get access to a CPU.

答案 1 :(得分:3)

当我运行这个程序时,它只打印一行而不是两行,因为它exit()的{​​{1}}块中有fork()个。

所以问题是,您是否忘记printf()块中的fork(),或exit()不应该在那里?

答案 2 :(得分:0)

如果要让一个进程先于另一个进程运行,请尝试使用sleep()系统调用。

相关问题