我对 fork() 如何从父进程复制内存感到非常困惑。我试图通过写一个例子来找出它:
int global_var = 0;
int main(int argc, char* argv[]){
int local_var = 1;
pid_t child;
child = fork();
if (child < 0){
cout << "Fork error: " << strerror(errno) << endl;
return 1;
}
if (child != 0 ){ // parent
cout << "Parent: global address: " << &global_var << endl;
cout << "Parent: local address: " << &local_var << endl;
++global_var;
++local_var;
cout << "Parent: global: " << global_var << endl;
cout << "Parent: local: " << local_var << endl;
}else{
cout << "Child: global address: " << &global_var << endl;
cout << "Child: local address: " << &local_var << endl;
sleep(1);
cout << "Child: global: " << global_var << endl;
cout << "Child: local: " << local_var << endl;
}
return 0;
}
我看到了结果:
父:全局地址:0x6021a0 父:本地地址:0x7fff942dd99c 父:全局:1 父:本地:2 子:全局地址:0x6021a0 子:本地地址:0x7fff942dd99c 子:全局:0 子:本地:1
为什么即使孩子的变量与父母的地址相同,孩子也没有看到变量的变化。有人可以帮我解释一下吗。
提前致谢。