根据man 5 proc
,可以使用/proc
文件系统在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.
我真的不想用 C 编写文本解析代码;我宁愿只调用操作系统并将信息直接读入结构。我查看了 /usr/include/linux
以查看是否有明显的 API 结构,但没有看到任何内容。
所以,两部分的问题:
- 这可以被认为是一个“坏主意”吗?也就是说,如果内核接口(interface)发生变化,用户程序是否应该硬着头皮从
/proc
中读取文本?如果是这样,是否有使用 C 从/proc
读取的公认“最佳实践”? (fscanf()
?正则表达式?) - 我将如何查找允许我直接读取这些数据的内核接口(interface)的文档(假设它们存在)? (内核源代码本身是最好的起点吗?如果是,我应该在内核源代码的哪个位置查看?)如果您知道哪个接口(interface)可以提供
/proc/[pid]/maps
具体数据。 =)
最佳答案
我认为对于 perl 或 shell 脚本来说,读取和解析/proc/数据非常好。在 C 程序中,如果需要健壮性,我会使用内核(可能是 sysctl
)接口(interface)。
原来 procps-bundled pmap implementation按如下方式逐行解析 /proc/PID/maps
文件(参见 one_proc()
函数):
sscanf(mapbuf,"%"KLF"x-%"KLF"x %31s %Lx %x:%x %Lu", &start, &end, flags, &file_offset, &dev_major, &dev_minor, &inode);
编辑:我的答案的原始版本显示了一种仅解析共享内存段上的数据的方法,而不是像 OP 所需的那样所有映射的内存段。
我相信 ipcs -m
将为您提供多个进程的相同数据。所以第二个问题的答案是你应该阅读 ipcs
代码:(例如 BSD version , Linux version ):
关于c - 使用 C 用户空间代码从 Linux/proc 接口(interface)读取的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9764639/