linux 进程pss,内存监控:用C++代码打印Linux中可访问进程的PSS(比例集合大小)...

内存监控:任何人都可以发布一个C++代码来打印Linux中可访问进程的PSS(比例集合大小)。

给定执行相同操作的python代码:

导入os、sys、re、pwd'''

Print the user name, pid, pss, and the command line for all accessable

processes in pss descending order.

'''

# Get the user name, pid, pss, and the command line information for all

# processes that are accessable. Ignore processes where the permission is

# denied.

ls = [] # [(user, pid, pss, cmd)]

for pid in filter(lambda x: x.isdigit(), os.listdir('/proc')):

try:

ls.append((owner_of_process(pid), pid, pss_of_process(pid), cmdline_of_process(pid)))

except IOError:

pass

# Calculate the max length of the user name, pid, and pss in order to

# print them in aligned columns.

userlen = 0

pidlen = 0

psslen = 0

for (user, pid, pss, cmd) in ls:

userlen = max(userlen, len(user))

pidlen = max(pidlen, len(pid))

psslen = max(psslen, len(str(pss)))

# Get the width of the terminal.

with os.popen('tput cols') as fp:

term_width = int(fp.read().strip())

# Print the information. Ignore kernel modules since they allocate memory

# from the kernel land, not the user land, and PSS is the memory

# consumption of processes in user land.

fmt = '%%-%ds %%%ds %%%ds %%s' % (userlen, pidlen, psslen)

print(fmt % ('USER', 'PID', 'PSS', 'COMMAND'))

for (user, pid, pss, cmd) in sorted(ls, lambda x, y: cmp(y[2], x[2])):

if cmd != '':

print((fmt % (user, pid, pss, cmd))[:term_width - 1])

def pss \u of \u进程(pid):

'''

返回pid指定进程的PSS,单位为KiB(1024字节)@param pid process ID

@return PSS value

'''

with file('/proc/%s/smaps' % pid) as fp:

return sum([int(x) for x in re.findall('^Pss:\s+(\d+)', fp.read(), re.M)])

def cmdline\U进程(pid):

'''

返回pid指定的进程的命令行。你知道吗@param pid process ID

@return command line

'''

with file('/proc/%s/cmdline' % pid) as fp:

return fp.read().replace('\0', ' ').strip()

def所有者\u进程(pid):

'''

返回pid指定的进程的所有者。你知道吗@param pid process ID

@return owner

'''

return pwd.getpwuid(os.stat('/proc/%s' % pid).st_uid).pw_name

如果名称=='main':

pss\u主()


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部