使用fork时如何映射内存? [英] How the memory is mapped when fork is used?
问题描述
我是"fork()"的新手,我到处都读到,当fork()被调用时,当前(调用)进程的精确副本已启动.有两个不同的内存位置分配给它们的变量和函数.
i am new to "fork()",I read everywhere that when a fork() is called an exact copy of current (calling) process is started.Now when I run following code ,there should be two different processes, having two different memory locations assigned to their vars and functions.
#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
为什么父母和孩子的地址都相同?
Why both the address are the same for parent as well as child?
推荐答案
为它们的var和函数分配了两个不同的存储位置.
having two different memory locations assigned to their vars and functions.
没有; Linux实现虚拟内存,这意味着每个进程都有自己的完整地址空间.结果,在fork
之后,两个进程的内存对象副本都将看到相同的地址.
Nope; Linux implements virtual memory, meaning that each process has its own complete address space. As a result, after a fork
, both processes see the same addresses for their copies of in-memory objects.
(顺便说一句:VM还会使代码在物理内存中的进程之间共享,并且所有数据将仅写入时复制.)
(As an aside: VM also causes code to be shared between the process in physical memory, and all data will only be copied-on-write.)
这篇关于使用fork时如何映射内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!