所以我在修订期间看到了以下代码。我知道wait()导致父进程等待子进程停止,但我对此有几个问题。
首先,当创建子进程时,我的假设是否得到纠正,即父进程继续,改变x值,然后在if语句之后等待?
其次,当子线程继续执行并调用wait()时,会发生什么?这是被忽视的,因为它没有什么可等待的?
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main() {
int x = 1;
pid_t pid = fork();
if (pid == 0) {
x = x * 2;
} else if (pid > 0) {
x = 3;
}
wait();
// Print the value of x to the console
printf("%dn",x);
}
您可以尝试在子线程执行开始时调用wait()。如果在此进程中没有子进程,则简单地忽略调用。