我是“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.)
原文地址:https://www.jb51.cc/linux/439906.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。