问题
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 ^_^
回答1:
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);
}
回答2:
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>
.
回答3:
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.
回答4:
Take a look at these questions and answers:
- Searching a process' memory on Linux
- Dump memory of a process
- Low-overhead way to access the memory space of a traced process?
来源:https://stackoverflow.com/questions/5030350/how-to-find-all-read-write-memory-address-of-a-process-in-linux-unix-with-c-c