为什么子进程和父进程的变量地址相同 [英] Why the address of variable of child process and parent process is same

查看:22
本文介绍了为什么子进程和父进程的变量地址相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

int main()
{
  pid_t pid;
  int y = 3;  
  if ( (pid = fork()) <0 )
   return -1;;

  if( pid == 0 )  /* child */
  {
    printf(" before: %d %p
", y, &y );
    y *= 10;
    printf("after: %d %p
", y, &y );
  }
  else /* father */
  {
   sleep(1);
   printf("father: %d %p
" , y , &y );

  }
  return 0;
}

程序的输出如下:

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?

推荐答案

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

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.

这篇关于为什么子进程和父进程的变量地址相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆