不同进程使用相同的内存地址 [英] Same memory address for different processes

查看:473
本文介绍了不同进程使用相同的内存地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想不出为什么这段代码会如此工作(而不是我所期望的):

I just can't figure out why this code works the way it does (rather than I'd expect):

 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <sys/wait.h>
 #include <sys/types.h>

 int main()
 {
     int buffer;
     int* address;

     address=&buffer;


     if(fork()==0)
     {
         *address=27;
         printf("Address %ld stores %d\n",(long)address,*address);
         exit(0);
     }
     wait(NULL);

     printf("Address %ld stores %d\n",(long)(&buffer),buffer);    
     return 0;
 }

为什么即使它们指向相同的内存地址,系统也会存储不同的变量?

Why does the system store different variables even if they're pointed to the same memory address?

注意:我从来没有真正期望过此代码能正常工作,因为否则整个管道和其他东西将毫无意义.我只想了解这里发生了什么.

NOTE: I never really expected this code to work, since otherwise the whole bunch of pipes and stuff wouldn't make any sense; I'd just like to understand what's going on here.

推荐答案

这不是一个真正的C问题,它涉及(现代)操作系统的行为.

This isn't really a C question, it's about the behavior of (modern) operating systems.

简而言之:现代操作系统上的用户空间程序在某些私有的虚拟地址空间中运行.访问内存时,虚拟地址将转换为物理地址.实际内存与虚拟地址空间之间的映射是由操作系统设置的-内存被拆分为页面,并且页面可以映射"到进程的地址空间中.

In short: A userspace program on a modern OS runs in some private virtual address space. When accessing memory, the virtual address is translated to a physical address. The mapping between actual memory and virtual address space is set up by the operating system -- the memory is split into pages and a page can be "mapped" into the address space of a process.

fork()通常只将相同的内存映射到它创建的第二个进程,但是一旦写入该内存,就将复制页面并映射副本(写入时复制").用户空间程序将永远不会看到其他用户空间程序专用的内存.

fork() typically just maps the same memory to the second process it creates, but as soon as this memory is written to, the page is copied and the copy is mapped ("copy on write"). A user space program will never see memory that is private to a different user space program.

我相信您可以轻松找到更多详细信息,以搜索此答案中给出的关键词.

I'm sure you can easily find more details searching for the key words given in this answer.

这篇关于不同进程使用相同的内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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