父子进程中数据地址的问题

myshasha 2010-08-01 12:00:23

int main()
{
int test = 0;
pid_t fork_resault;
fork_resault = fork();

if(fork_resault == 0){
sleep(5);
test++;
printf("child: test = %d, &test = %X\n",test, &test);
} else {
test ++;
printf("parent: test = %d, &test = %X\n",test, &test);
}
}


Ubuntu 8.10 运行输出结果:
parent: test = 1, &test = BFBD7048
child: test = 1, &test = BFBD7048

问题:parent和child中&test怎么都一样的呢?

linux中不是对进程中的页是写时复制的么,那在++后子进程中数据应该到新的页框中去了,那&test的结果不就应该不同了么?请高手帮忙,谢谢。
...全文
101 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
myshasha 2010-08-02
  • 打赏
  • 举报
回复
嗯,谢谢,基本能够理解了。
zgolee 2010-08-01
  • 打赏
  • 举报
回复
楼上正解
谭海燕 2010-08-01
  • 打赏
  • 举报
回复
一条一条的给你分析:
1.如果test的地址是一样的,也即是说parent和child中的test是同一个,那么,无论parent和child那个

进程先运行,test++的结果不可能等于1.也就是说,必须有一个test == 2 才对

2.每个进程都有自己一个独立的栈,以及内存区,parent和child是不会共享的.

In Linux, fork() is implemented through the use of copy-on-write pages. Copy-on-write (or COW) is a technique to delay or altogether prevent copying of the data. Rather than duplicate the process address space, the parent and the child can share a single copy. The data, however, is marked in such a way that if it is written to, a duplicate is made and each process receives a unique copy

COW,就是复制到各个进程自己的内存空间里去。所以。parent中的 BFBD7048和child中的 BFBD7048

不是同一个地址,只是相对改进程地址空间的offset或者,其实就是一个虚拟地址。child和parent,在他们

自己看来,自己拥有了全部的内存空间,而感觉不到其他的进程的存在,child感觉不到parent也同样有一块

内存空间。



希望你能理解我上面的解释。

4,465

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 内核源代码研究区
社区管理员
  • 内核源代码研究区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧