Linux下C语言量化进程的RAM、CPU使用情况
如何找出 Linux 中某个进程“吃掉”了多少 RAM 和 CPU?如何找出所有运行的进程(包括守护进程和系统进程)? =)
UPD: 使用C语言
How to find out, how much RAM and CPU "eats" certain process in Linux? And how to find out all runned processes (including daemons and system ones)? =)
UPD: using C language
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 top 或 ps.
例如,
ps aux
将列出所有进程及其所有者、状态、使用的内存等。编辑:要在 Linux 下使用 C 语言执行此操作,您需要阅读处理 proc 文件系统中的文件。例如,
/proc/1/status
包含有关您的 init 的信息进程(始终具有PID 1
):Use top or ps.
For example,
ps aux
will list all processes along with their owner, state, memory used, etc.EDIT: To do that with C under Linux, you need to read the process files in the proc filesystem. For instance,
/proc/1/status
contains information about your init process (which always hasPID 1
):测量一个进程使用了多少内存几乎是不可能的。困难在于,每块内存并不完全由一个进程使用,并且进程使用的所有内存实际上并不都由该进程“拥有”。
例如,两个进程可以共享同一文件的映射,在这种情况下,位于映射核心的任何页面都将“属于”这两个进程。但如果这些进程中只有一个正在使用它呢?
如果进程已分叉,或者已映射但尚未使用,私有页面也可以是写时复制(考虑进程已分配了一个巨大区域但尚未触及其中大部分区域的情况)。在这种情况下,哪个进程“拥有”这些页面?
进程还可以有效地使用部分缓冲区高速缓存和许多其他类型的内核缓冲区,这些缓冲区不属于它们“拥有”。
有两个可用的测量值,即 VM 大小(进程刚刚映射了多少内存)和驻留集大小 (RSS)。它们都没有真正告诉您进程使用了多少内存,因为它们都计算共享页面,但都不计算非映射页面。
那么有答案吗?其中一些可以通过检查 /proc (/proc/pid/pagemap) 中现有的页面映射结构来测量,但不一定有一种简单的方法来共享共享页面的“所有权”。
有关对此的讨论,请参阅 Linux 的 Documentation/vm/pagemap.txt。
Measuring how much ram a process uses is nearly impossible. The difficulty is, that each piece of ram is not used by exactly one process, and not all ram a process is using is actually "owned" by it.
For example, two processes can have shared mappings of the same file, in which case any pages which are in core for the mapping, would "belong" to both processes. But what if only one of these processes was using it?
Private pages can also be copy-on-write if the process has forked, or if they have been mapped but not used yet (consider the case where a process has malloc'd a huge area but not touched most of it yet). In this case, which process "owns" those pages?
Processes can also be effectively using parts of the buffer cache and lots of other kinds of kernel buffers, which aren't "owned" by them.
There are two measurements which are available, which are VM Size, (how much memory the process has mapped just now) and resident set size (RSS). Neither of them really tells you much about how much memory a process is using, because they both count shared pages and neither counts non-mapped pages.
So is there an answer? Some of these can be measured by examining the page maps structures which are now available in /proc (/proc/pid/pagemap), but there isn't necessarily a trivial way of sharing out the "ownership" of shared pages.
See Linux's Documentation/vm/pagemap.txt for a discussion of this.