今天程序哥说机器不断死机,后发现是swap用完了导致,现需要找出哪些进程占用了swap,网上找了一下办法,就是查看/proc下面的进程号目录里面的smaps文件,如下:
tail -n 18 /proc/19454/smaps
- ffde1000-ffdf6000 rw-p 7ffffffea000 00:00 0 [stack]
- Size: 84 kB
- Rss: 8 kB
- Shared_Clean: 0 kB
- Shared_Dirty: 0 kB
- Private_Clean: 0 kB
- Private_Dirty: 8 kB
- Swap: 0 kB
- Pss: 8 kB
- ffffe000-fffff000 r-xp ffffe000 00:00 0
- Size: 4 kB
- Rss: 4 kB
- Shared_Clean: 4 kB
- Shared_Dirty: 0 kB
- Private_Clean: 0 kB
- Private_Dirty: 0 kB
- Swap: 0 kB
- Pss: 0 kB
这里中间有几行“Swap 0 kB”,将文件中所有这些行的值加起来就是这个进程占用的SWAP值,有方法了就写成脚本吧,Python脚本如下:
- #!/usr/bin/python
- #coding:utf-8
- #列出系统进程占用SWAP的情况!
- import re
- import sys
- import os
- def check(pid):
- #获取SWAP大小
- file_smaps = '/'.join(["/proc",pid,"smaps"])
- f = open(file_smaps,'r')
- content1 = f.read()
- f.close()
- pattern1 = r'Swap:\s+(.*)\s+kB'
- find1 = re.compile(pattern1)
- sum = 0
- for size in find1.findall(content1):
- sum = sum + int(size)
- #获取进程名称
- file_status = '/'.join(["/proc",pid,"status"])
- s = open(file_status, 'r')
- content2 = s.read()
- s.close()
- pattern2 = r'Name:\s+(.*)'
- find2 = re.compile(pattern2)
- name = find2.findall(content2)[0]
- return name,sum
- if __name__ == "__main__":
- print "脚本将列出有占用SWAP的程序ID和占用的SWAP大小:"
- print "%-5s %-10s %s" % ('PID','SWAP(kB)','NAME')
- print "----------------------------------------------------"
- for pid in os.listdir("/proc"):
- if pid.isdigit():
- name,size = check(pid)
- if size:
- print "%-5s %-10s %s" % (pid, size, name)
运行效果如下图: