2

Through /proc file system , it's probable to read memory mappings with /proc/PID_PROCESS/maps , but is there any native APIs that dedicated for this function in C/C++ ?

i.e to find out memory address that are writable and readable for process with 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

And those address are passed into my program , but now i want to integrate this function directly into my C++ program.

For most effectiveness , if i want to support for other *BSD system , i would not be able to take advantage of /proc system , and i think there should some method to generate e.g /proc/1/maps directly without reading them again there , correct if i'm wrong ^_^

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
daisy
  • 22,498
  • 29
  • 129
  • 265

4 Answers4

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

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
jwir3
  • 6,019
  • 5
  • 47
  • 92
1

Unfortunately, there is no full library (to my knowledge) to do what you want here. There is a libproc as part of procps, however this is an internal API, and moreover probably only implements the functionality used by procps. It would certainly be nice if there was such a library - feel free to release one! - but for now you'll have to conditional-compile for each OS you're targetting, and use OS-specific APIs (for Linux, directly opening and reading the appropriate procfiles) directly.

bdonlan
  • 224,562
  • 31
  • 268
  • 324
  • Thanks for answering this questing , i didn't really tried libproc , but you are right , i should try to release one ;-P – daisy Mar 29 '11 at 08:34
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);
  }
Constantin
  • 8,721
  • 13
  • 75
  • 126
Zimbabao
  • 8,150
  • 3
  • 29
  • 36
  • Thanks Zim , but is there any native API's that i don't need to parse /proc file system ? Because on some BSD UNIX system , there's no /proc file system , i would be happy if my program is portable amid most of *BSD system ;-P – daisy Feb 17 '11 at 14:53
  • AFAIK there is no native API for that. You can write parser for each BSD, Linux and selectively compile using flags. – Zimbabao Feb 17 '11 at 15:01
  • Sure , and i've implemented one with simple file reading and parsing , i'll take this one as the best answer for now. – daisy Mar 29 '11 at 08:33
0

Take a look at these questions and answers:

Community
  • 1
  • 1
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526