我是「fork()」的新手,我在任何地方都會看到,當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);
}
Why The output looks like:: child address::804a01c parent address::804a01c
爲什麼這兩個地址是家長以及孩子一樣嗎?
他們*最好*是一樣的。您希望指針在兩個進程中以相同的方式引用內存(即使兩個內存塊都不同)。閱讀*虛擬內存*,這將回答你的問題。 – 2012-03-15 17:00:58
請注意,即使兩個副本都存儲在相同的虛擬地址,父節點與子節點之間的'i'的*值*也是不同的。 – markgz 2012-03-15 18:19:54