Identifying which processes have pages swapped out of memory when troubleshooting performance issues on a Linux system is often helpful. Swapping can impact system performance, so knowing which processes are affected is important in diagnosing and resolving these issues.
Checking Swap Usage by Process
Linux provides detailed process information in the /proc
directory. By leveraging this, you can extract each process’s swap memory usage with a simple bash command.
The Command
Run the following command in your terminal to display the amount of swap memory used per process:
1 |
for file in /proc/*/status; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -nr | head -20 |
Explanation
1. Iterating through /proc:
The command processes every status file under /proc, which contains metadata about each running process.
2. Extracting Relevant Information:
The awk command searches for lines containing VmSwap (swap usage in kilobytes) and Name (process name).
It prints the process name and its swap usage on the same line.
3. Sorting Results:
The sort command organizes the output numerically in descending order based on the second column (swap usage).
4. Filtering Results:
The head command filters the top 20 processes using swap
Sample Output
Here’s an example of what the output might look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# for file in /proc/*/status; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -nr | head -20 sssd_kcm 3163528 kB mongod 184936 kB rpc.gssd 184332 kB mongod 163300 kB mysqld 97240 kB mongod 94412 kB mongod 52744 kB mongod 51904 kB mongod 42560 kB mongod 42412 kB mongod 39540 kB mysqld 25768 kB clickhouse-serv 10948 kB dockerd 8112 kB clickhouse-serv 6492 kB containerd 3856 kB datacollector 3036 kB docker-proxy 2616 kB docker-proxy 2412 kB docker-proxy 2152 kB |
Conclusion
The above command quickly identifies processes that are consuming swap memory and addresses potential performance bottlenecks. This lightweight, native approach is particularly useful for Linux administrators and developers seeking to optimize system performance without relying on additional tools.