且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么子进程和父进程的变量地址相同

更新时间:2022-06-22 04:24:40

因为它是一个虚拟地址,而不是一个物理地址.

Because it's a virtual address, not a physical one.

每个进程都有自己的地址空间(例如,32位系统可能允许每个进程拥有自己的地址空间,全4G范围).

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).

下图可能会有所帮助,每个部分代表一个 4K 内存块:

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.

中心块中的地址是数据真正"所在的实际物理地址,由 MMU 处理映射.

The addresses in the central block are actual physical addresses where the data "really" is, and the MMU handles the mapping.

对于fork(和exec)的更深入解释,您可能还想查看这个答案.

For a deeper explanation of fork (and exec), you may also want to look at this answer.