我是“fork()”的新手,我随处读到,当调用fork()时,启动当前(调用)进程的精确副本.现在,当我运行以下代码时,应该有两个不同的进程,有两个不同的分配给其变量和函数的内存位置.
#includedio.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);
}
Why The output looks like:: child address::804a01c parent address::804a01c
为什么父母和孩子的地址都是一样的?
最佳答案
having two different memory locations assigned to their vars and functions.
不; Linux实现了virtual memory,这意味着每个进程都有自己的完整地址空间.因此,在fork之后,两个进程都会看到内存对象副本的相同地址.
(顺便说一下:VM还会导致代码在物理内存中的进程之间共享,并且所有数据都只是copied-on-write.)