我是“fork()”的新手,我到处都读到当fork()被调用时,当前(调用)进程的精确副本已启动。现在,当我运行以下代码时,应该有两个不同的进程,其中有两个不同的进程分配给它们的变量和函数的内存位置。
#include<stdio.h>
int i=10;
int pid;
int main(){
if((pid=fork())==0){
i++;//somewhere I read that separate memory space for child is created when write is needed
printf("parent address= %p\n",&i);// this should return the address from parent's memory space
}else{
i++;
i++;
printf("child address= %p\n",&i);// this should return the address of child's memory space
}
wait(0);
return(0);
}
为什么输出如下:
子地址:: 804a01c
父地址:: 804a01c
为什么 parent 和 child 的地址都相同?
最佳答案
不; Linux实现virtual memory,这意味着每个进程都有自己的完整地址空间。结果,在fork
之后,两个进程对于其内存中对象的副本将看到相同的地址。
(顺便说一句:VM还会使代码在物理内存中的进程之间共享,并且所有数据只会是copied-on-write。)