谁能解释一下为什么下面程序的输出是1而不是2?
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int x = 1;
int *y = &x;
pid_t pid = fork();
if (pid == 0) {
*y = 2;
exit(0);
} else {
wait(NULL);
printf("father: %d\n", x);
}
return 1;
}
最佳答案
fork
不会创建线程,而是创建一个全新的进程。
子进程的地址空间是父进程的地址空间的副本,他们不共享它。
父级所做的修改对于子级来说是不可见的,反之亦然,除非专门设置了一些东西(例如通过共享内存段)。
关于c - 在子进程中操作来自父亲的 var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10586511/