通过系统调用监控Linux上的内存
我一直在寻找一种测量 Linux 上内存使用情况的方法。我发现了三种主要的方法,但我不确定应该使用什么,因此我在这里征求意见。
这似乎是最广泛且可能更简单的方法 监控内存就是读取/proc/pid/status并读取 适当的字段,
VmSize
、VmData
或其他。这就是方法 程序 ps、to、vmstat 设法收集这些信息(我的意思是, 监控/proc/pid/...)。该信息将提供 瞬时信息。我可以调用一个fork,然后调用一个exec来运行我想要的程序 监视并等待 4 来填充 rusage 结构。从那里 我可以读取所需的字段。似乎在 Linux 中, wait4 不会填充 rsusage 结构中的内存字段,而只是填充 cpu 使用率相关字段。这是时间命令的获取方式 它的信息。
我可以更改 strace 代码,以跟踪所有后续的 brk, mmap、munmap 系统调用,并求和以获得堆大小。这 这里的困难是解码所有可能的 mmap 参数以供读取 仅,读|写,执行等,并测试返回值以了解是否 系统成功。
对于3),你认为我可以通过这种方式测量内存使用情况吗?会不会太难了?我对 strace 代码有很好的理解,但我对记忆的理解不够,不知道这是否可能。
I have been looking around for a way to measure memory usage on Linux. I found out three main ways of doing it and I am not sure what should I use, therefore I am asking here for opinions.
It seems that the most widespread and maybe easier way of
monitoring memory is to read /proc/pid/status and read the the
appropriate field,VmSize
,VmData
or whatever. This is the way the
programs ps, to, vmstat manage to colect this information(I mean,
monitoring /proc/pid/...). This information will provide
instantanous information.I can call a fork followed by an exec to run the program I want
to monitor and wait4 to get to fill an rusage structure. From there
I can read the desired field. It seems though that in Linux, the
wait4 does not fill memory fields in the rsusage structure, but only
the cpu usage related fields. This is the way the time command gets
its infortions.I can change strace code, to keep track of all suceeding brk,
mmap, munmap system calls, and sum up to get heap size. The
difficult here would be decode all possible mmap arguments for read
only, read|write, exec etc, and test return values to know if the
system succeeded.
For 3), Do you think I can measure memory usage this way? Would that be too difficult? I have a good understanding of strace code, but I do not understand enough from memory, to know if this is possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的程序只对使用 malloc() 完成的内存分配感兴趣,您可以查看 mallinfo()。
If your program is only interested in memory allocations done using malloc(), you could have a look to mallinfo().
在 Linux 上,有关内存映射的更精确信息可通过
pmap
以及/proc/self/maps
或/proc/1234/maps
获得文件(其中 1234 是进程 ID)。尝试 cat /proc/self/maps 来了解更多信息。On Linux, more precise information about memory maps are available thru
pmap
and with the/proc/self/maps
or/proc/1234/maps
file (where 1234 is the process id). Trycat /proc/self/maps
to understand more.