在Linux下,如何发现哪个进程使用交换空间更多?


当前回答

运行top,然后按OpEnter。现在进程应该根据它们的交换使用情况进行排序。

这是一个更新,因为我原来的答案没有提供一个确切的答案,在评论中指出的问题。从htop常见问题:

It is not possible to get the exact size of used swap space of a process. Top fakes this information by making SWAP = VIRT - RES, but that is not a good metric, because other stuff such as video memory counts on VIRT as well (for example: top says my X process is using 81M of swap, but it also reports my system as a whole is using only 2M of swap. Therefore, I will not add a similar Swap column to htop because I don't know a reliable way to get this information (actually, I don't think it's possible to get an exact number, because of shared pages).

其他回答

运行top,然后按OpEnter。现在进程应该根据它们的交换使用情况进行排序。

这是一个更新,因为我原来的答案没有提供一个确切的答案,在评论中指出的问题。从htop常见问题:

It is not possible to get the exact size of used swap space of a process. Top fakes this information by making SWAP = VIRT - RES, but that is not a good metric, because other stuff such as video memory counts on VIRT as well (for example: top says my X process is using 81M of swap, but it also reports my system as a whole is using only 2M of swap. Therefore, I will not add a similar Swap column to htop because I don't know a reliable way to get this information (actually, I don't think it's possible to get an exact number, because of shared pages).

Iotop是一个非常有用的工具。它提供了每个进程/线程的I/O和交换使用情况的实时统计数据。默认情况下,它显示每个线程,但你可以执行iotop -P来获取每个进程的信息。默认情况下,这是不可用的。您可能需要通过rpm/apt安装。

另一种在shell中避免循环的脚本变体:

#!/bin/bash
grep VmSwap /proc/[0-9]*/status | awk -F':' -v sort="$1" '
  {
    split($1,pid,"/") # Split first field on /
    split($3,swp," ") # Split third field on space
    cmdlinefile = "/proc/"pid[3]"/cmdline" # Build the cmdline filepath
    getline pname[pid[3]] < cmdlinefile # Get the command line from pid
    swap[pid[3]] = sprintf("%6i %s",swp[1],swp[2]) # Store the swap used (with unit to avoid rebuilding at print)
    sum+=swp[1] # Sum the swap
  }
  END {
    OFS="\t" # Change the output separator to tabulation
    print "Pid","Swap used","Command line" # Print header
    if(sort) {
      getline max_pid < "/proc/sys/kernel/pid_max"
      for(p=1;p<=max_pid;p++) {
        if(p in pname) print p,swap[p],pname[p] # print the values
      }
    } else {
      for(p in pname) { # Loop over all pids found
        print p,swap[p],pname[p] # print the values
      }
    }
    print "Total swap used:",sum # print the sum
  }'

标准用法是script.sh以随机顺序获取每个程序的使用情况(直到awk如何存储其哈希值)或script.sh 1以pid对输出进行排序。

我希望我已经对代码进行了足够的注释,以说明它的功能。

我不知道如何确切地找到哪个进程正在使用交换空间的直接答案,但是,这个链接可能会有帮助。另一个好例子在这里

另外,使用像htop这样的好工具来查看哪些进程使用了大量内存,以及总体上使用了多少交换空间。

不完全清楚您的意思是要找到交换出最多页的进程还是导致交换出最多页的进程。

对于前者,您可以运行top并按swap排序(按'Op'),对于后者,您可以运行vmstat并查找'so'的非零条目。