Why the address of variable of child process and parent process is same

六眼飞鱼酱① 提交于 2019-11-26 22:47:24
paxdiablo

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:

   Process A           Physical Memory      Process B
   +-------+           +-------------+      +-------+
0K |       |---->   0K |  (shared)   | <----|       | 0K
   +-------+           +-------------+      +-------+
4K |       |--+     4K |             | <----|       | 4K
   +-------+  |        +-------------+      +-------+
8K |       |  +->   8K |             |      |       | 8K
   +-------+           +-------------+      +-------+
       |                : : : : : : :           |
       |               +-------------+          |
       |          128K |             | <--------+
       |               +-------------+
       +--------> 132K |             |
                       +-------------+

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 (and exec), 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!