如何访问分配给不同进程的内存? [英] how to access memory allocated to different process?

查看:35
本文介绍了如何访问分配给不同进程的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编辑了 1.c 如下.

I have edited 1.c as below.

#include<stdio.h>
int x=100;
int main(void)
{
    printf("%p",&x);
    while(1);
    return 0;
}

然后我打开命令提示符并运行该程序并在程序仍在运行时得到输出 00402000.现在我运行 2.c

Then I opened Command Prompt and run this program and got Output 00402000 while program still running. Now I run 2.c

#include<stdio.h>
int main(void)
{
    int *p=(int *)0x00402000;
    printf("%d",*p);
    return 0;
}

在命令提示符的另一个实例中并得到输出 -1,我期望 100 位于位置 00402000.请解释为什么会出现这种行为?

in another instance of command prompt and got output -1, I expect 100 which is in location 00402000. please explain why is this behavior?

推荐答案

首先,让我说在现代操作系统中,您的程序看到的地址值(例如 0x00402000)不是 物理地址.它们是虚拟地址,它们对拥有进程是私有的(即在其他进程中没有意义或意味着其他东西),并且通过基于 CPU 的机制(分页单元")映射到物理地址,只有操作系统才有控制.

First and foremost, let me say that in modern operating systems, the address values that your program sees (like that 0x00402000) are not physical addresses. They are virtual addresses, they're private to the owning process (i. e. make no sense or mean something else in other processes), and are mapped to physical addresses via a CPU-based mechanism ("the paging unit") that only OS has control over.

如果你想在不同的进程之间共享一个变量,有一种机制叫做共享内存.仔细阅读它.相关的API是CreateFileMapping,第一个参数是INVALID_HANDLE_VALUEMapViewOfFileOpenFileMapping.还有其他的进程间通信方式.

If you want to share a variable between different processes, there's a mechanism called shared memory. Read up on it. The relevant APIs are CreateFileMapping with the the first parameter being INVALID_HANDLE_VALUE, MapViewOfFile, OpenFileMapping. There are other ways of interprocess communication, too.

如果你想在没有进程明确合作的情况下读取进程的内存,你需要阅读调试API.这比使用共享内存要复杂得多.

If you want to read process' memory without that process' explicit cooperation, you need to read up on debugging API. This is a much trickier job than using shared memory.

顺便说一下,您编写的代码是典型的未定义行为.

What you've coded, by the way, is a classic undefined behavior.

这篇关于如何访问分配给不同进程的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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