我想知道如何使用/proc/stat
和/proc/status
文件计算进程的 CPU 和内存利用率。我可以计算用户使用的总内存和 CPU 吗?
答案1
ps
是最简单的信息接口/proc
。
以下是列出每个用户内存的一种方法:
$ ps -e -o uid,vsz | awk '
{ usage[$1] += $2 }
END { for (uid in usage) { print uid, ":", usage[uid] } }'
如果你真的想使用 proc,我建议使用 Python 或 Perl 之类的东西来迭代一次/proc/*/status
,并将用户/使用键/值对存储在哈希中。
的相关字段/proc/PID/status
似乎是:
Uid: 500 500 500 500
VmSize: 1234 kB
我认为这四个 Uid 数字是真实 uid、有效 uid、保存 uid 和 fs uid。
假设你想要真正的 uid,类似这样的东西应该可以工作:
# print uid and the total memory (including virtual memory) in use by that user
# TODO add error handling, e.g. not Linux, values not in kB, values not ints, etc.
import os
import sys
import glob
# uid=>vsz in KB
usermem = {}
# obtain information from Linux /proc file system
# http://www.kernel.org/doc/man-pages/online/pages/man5/proc.5.html
os.chdir('/proc')
for file in glob.glob('[0-9]*'):
with open(os.path.join(file, 'status')) as status:
uid = None
mem = None
for line in status:
if line.startswith('Uid:'):
label, ruid, euid, suid, fsuid = line.split()
uid = int(ruid)
elif line.startswith('VmSize:'):
label, value, units = line.split()
mem = int(value)
if uid and mem:
if uid not in usermem:
usermem[uid] = 0
usermem[uid] += mem
for uid in usermem:
print '%d:%d' % (uid,usermem[uid])
CPU就更难了。
ps(1) 手册页显示:
CPU usage is currently expressed as the percentage of time spent running during the entire lifetime of a process. This is not ideal, and it does not conform to the standards that ps otherwise conforms to. CPU usage is unlikely to add up to exactly 100%.
所以我不确定。也许看看top
它是如何处理的。或者你可以ps -e -o uid,pid,elapsed
在给定的时间间隔运行两次,然后减去两次,或者其他什么。
或者安装更适合此目的的东西,例如流程会计。
答案2
您可以检查该/proc/meminfo
文件:
cat /proc/meminfo | head -2
MemTotal: 2026816 kB
MemFree: 377524 kB
使用上面的两个条目,您可以计算出当前使用了多少内存:
cat /proc/meminfo | head -2 | awk 'NR == 1 { total = $2 } NR == 2 { free = $2 } END { print total, free, total - free }'