2

通过 /proc 文件系统,可以使用 /proc/PID_PROCESS/maps 读取内存映射,但是在 C/C++ 中是否有专门用于此功能的本机 API?

即找出对于 PID 9322 的进程可写和可读的内存地址:

%> awk -F "-| " '$3 ~ /rw/ { print $1 " " $2}' /proc/9322/maps
0804e000 0804f000
085ed000 0860e000
b7707000 b7708000
b7864000 b7865000
b7865000 b7868000
b7897000 b7898000
b78b6000 b78b7000
bfd2e000 bfd50000

这些地址被传递到我的程序中,但现在我想将此函数直接集成到我的 C++ 程序中。

为了最有效,如果我想支持其他 *BSD 系统,我将无法利用 /proc 系统,我认为应该有一些方法可以直接生成 /proc/1/maps 而不在那里再次读取它们,如果我错了,请纠正^_^

4

4 回答 4

1

Well, you could grab the PID of the process using:

pid_t pid = getpid();

Then, you could open the file /proc/PID/maps to and parse it into an array to determine which sets of memory are read-write.

Edit: The getpid() function requires #include <unistd.h>.

于 2011-02-17T14:46:14.693 回答
1

不幸的是,没有完整的图书馆(据我所知)在这里做你想做的事。作为 procps的libproc一部分,但这是一个内部 API,而且可能只实现 procps 使用的功能。如果有这样的库肯定会很好 - 随意发布一个!- 但现在你必须为你所针对的每个操作系统进行条件编译,并直接使用操作系统特定的 API(对于 Linux,直接打开和读取适当的 procfiles)。

于 2011-02-17T15:06:51.917 回答
0

Read the proc file like you read normal file.

eg.

  FILE *filep = fopen("/proc/9322/maps","r");
  char ch;
  while (ch != EOF){
    ch = fgetc(filep);
    printf("%c", ch);
  }
于 2011-02-17T14:48:46.273 回答
0

看看这些问题和答案:

于 2011-02-17T15:08:38.000 回答