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

C 在fork()程序中,首先执行什么?父母还是孩子?,c,unix,fork,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 或 没有具体说明。由操作系统调度器决定首先调度哪个进程 After a

我不知道在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


没有具体说明。由操作系统调度器决定首先调度哪个进程

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.

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

当我运行此程序时,它只打印一行,而不是两行,因为它
exit()
s在
fork()
的块中


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

你得到了哪个结果?不。我的计算机上没有任何C编译器,我必须学习考试。我只打印了一行(见下面的答案)。代码有缺陷
fork()
不会创建与父线程共享
n
变量的新线程。它创建了一个完整的新流程,因此
n=n+1
在共同情况下将在父流程中可见。要测试哪个进程先执行(如果您仍然感兴趣),请从两个进程访问共享资源,例如文件。代码正确。。。我只是不知道它到底是干什么的。:)如果代码正确,它将只打印一行:
xxx:3\n
,其中xxx是父进程的PID。这是同步进程的糟糕方法(您将睡眠多长时间?)。这并没有回答真正的问题。这个问题已经由Karoly Horvath回答了,所以我只想补充一些东西。我只是想让他知道sleep()系统调用。
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.