According to man 5 proc, one can use the /proc filesystem to access the following information on Linux:
/proc/[pid]/maps
A file containing the currently mapped memory regions and their access
permissions.
The format is:
address perms offset dev inode pathname
08048000-08056000 r-xp 00000000 03:0c 64593 /usr/sbin/gpm
08056000-08058000 rw-p 0000d000 03:0c 64593 /usr/sbin/gpm
08058000-0805b000 rwxp 00000000 00:00 0
40000000-40013000 r-xp 00000000 03:0c 4165 /lib/ld-2.2.4.so
40013000-40015000 rw-p 00012000 03:0c 4165 /lib/ld-2.2.4.so
4001f000-40135000 r-xp 00000000 03:0c 45494 /lib/libc-2.2.4.so
40135000-4013e000 rw-p 00115000 03:0c 45494 /lib/libc-2.2.4.so
4013e000-40142000 rw-p 00000000 00:00 0
bffff000-c0000000 rwxp 00000000 00:00 0
where "address" is the address space in the process that it occupies,
"perms" is a set of permissions:
r = read
w = write
x = execute
s = shared
p = private (copy on write)
"offset" is the offset into the file/whatever, "dev" is the device
(major:minor), and "inode" is the inode on that device. 0 indicates
that no inode is associated with the memory region, as the case would
be with BSS (uninitialized data).
Under Linux 2.0 there is no field giving pathname.
I don’t really want to be writing text parsing code in C; I’d rather just make calls to the OS and read the information directly into structures. I looked in /usr/include/linux to see if there was an obvious structure with APIs, but didn’t see anything.
So, two part question:
- Can this be considered a “bad idea”? That is, should user programs just bite the bullet and read text from
/procin case the kernel interfaces change? If so, is there an accepted “best practice” for reading from/procusing C? (fscanf()? Regular expressions?) - How would I go about finding the documentation for the kernel interfaces (assuming they exist) which would allow me to directly read this data? (Is the kernel source itself the best place to start? If so, where in the kernel source should I look?) Bonus points if you know what interface can provide the
/proc/[pid]/mapsdata specifically. =)
I think for a perl or shell script it’s perfectly fine to read and parse the /proc/ data. In a C program, if robustness is required, I would use a kernel (probably a
sysctl) interface.Turns out that the procps-bundled pmap implementation parses
/proc/PID/mapsfiles line-by-line as follows (seeone_proc()function):EDIT: Original version of my answer showed a way to parse data on shared memory segments only, not all mapped memory segments as the OP desired.
I believe
ipcs -mwill give you the same data for multiple processes. So the answer to your second question is that you should read theipcscode: (e.g BSD version, Linux version):