为什么子进程和父进程的变量地址相同
这是我的代码
int main()
{
pid_t pid;
int y = 3;
if ( (pid = fork()) <0 )
return -1;;
if( pid == 0 ) /* child */
{
printf(" before: %d %p\n", y, &y );
y *= 10;
printf("after: %d %p\n", y, &y );
}
else /* father */
{
sleep(1);
printf("father: %d %p\n" , y , &y );
}
return 0;
}
程序的输出如下:
before: 3 ffbff440
after: 30 ffbff440
father: 3 ffbff440
我的问题是为什么子变量和父变量的地址相同但值不同?
Here is my code
int main()
{
pid_t pid;
int y = 3;
if ( (pid = fork()) <0 )
return -1;;
if( pid == 0 ) /* child */
{
printf(" before: %d %p\n", y, &y );
y *= 10;
printf("after: %d %p\n", y, &y );
}
else /* father */
{
sleep(1);
printf("father: %d %p\n" , y , &y );
}
return 0;
}
The output of the program is like following:
before: 3 ffbff440
after: 30 ffbff440
father: 3 ffbff440
My question is why is address of variable of child and parent same but the value different?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为它是一个虚拟地址,而不是物理地址。
每个进程都有自己的地址空间(例如,32 位系统可能允许每个进程拥有自己的完整 4G 范围的地址空间)。
它是内存管理单元,它将虚拟地址映射到物理地址(如果需要从辅助存储买回换出的页面,则处理页面错误等问题)。
下图可能会有所帮助,每个部分代表一个 4K 内存块:
在该图中,您可以看到虚拟内存地址和物理内存地址之间的脱节(以及进程共享内存块的可能性)。左右两侧的地址是进程看到的虚拟地址。
中央块中的地址是数据“真正”所在的实际物理地址,并且由 MMU 处理映射。
要更深入地解释
fork
(和exec
),您可能还需要查看 这个答案。Because it's a virtual address, not a physical one.
Each process gets its own address space (for example, a 32-bit system may allow each process to have its own address space with the full 4G range).
It's the memory management unit that will map virtual addresses to physical ones (and handle things like page faults if swapped out pages need to be bought back in from secondary storage).
The following diagram may help, each section representing a 4K block of memory:
You can see, in that diagram, the disconnect between virtual memory addresses and physical memory addresses (and the possibility for processes to share memory blocks as well). The addresses down the left and right sides are virtual addresses which the processes see.
The addresses in the central block are actual physical addresses where the data "really" is, and the MMU handles the mapping.
For a deeper explanation of
fork
(andexec
), you may also want to look at this answer.地址是“相同的”,因为每个进程都有自己的虚拟地址空间,并且变量通常会加载到相同的位置。请注意,这不是内存中的物理地址。另请注意,有些方案故意随机化进程加载的位置,以使攻击/破解进程变得更加困难。在这种情况下,地址将会不同。
The address is the 'same' as each process has its own virtual address space and the variable will generally be loaded into the same location. Note that this is not the physical address in memory. Also note that there are schemes that deliberately randomise the location at which a process is loaded in order to make it harder to attack/hack the process. In that case the address will be different.