今天程序哥說機器不斷死機,後發現是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)
運行效果如下圖: