Top 3 processes by memory usage
Problem statement
A host is swapping. You captured ps aux into ps.txt. Print the 3 processes using the most memory (%MEM, column 4) as PID %MEM COMMAND, highest first. The header must not be treated as data, and commands that contain spaces must be printed in full.
ps.txt
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDroot 1 0.0 0.1 167812 11520 ? Ss Sep20 0:12 /sbin/initpostgres 812 1.2 18.4 4212340 1498220 ? Ss Sep20 45:10 postgres: mainwww-data 1044 0.8 6.2 1843200 505344 ? Sl Sep20 12:03 nginx: worker processdeploy 2210 35.0 22.7 5820112 1848320 ? Sl 09:14 80:22 java -jar api.jarroot 640 0.3 1.1 1320400 90112 ? Ssl Sep20 3:40 /usr/bin/containerddeploy 2388 2.1 9.5 2201600 773120 ? Sl 09:20 5:01 node worker.jsroot 3001 0.0 0.0 7060 3200 pts/0 R+ 10:02 0:00 ps auxExamples
Example 1
Input: Run the command on `ps.txt`.
Output: 2210 22.7 java -jar api.jar
812 18.4 postgres: main
2388 9.5 node worker.js
Hints
Approach
tail -n +2 prints from line 2 onward, dropping the header. sort -k4,4nr sorts numerically in reverse on column 4 only, which is %MEM; sort splits on runs of blanks by default. head -n 3 keeps the top three. The awk step prints the PID ($2) and %MEM ($4), then rebuilds the command by joining fields 11 to NF with spaces, because a command like java -jar api.jar is split across several fields.
tail -n +2 ps.txt | sort -k4,4nr | head -n 3 | awk '{ cmd = $11; for (i = 12; i <= NF; i++) cmd = cmd " " $i; print $2, $4, cmd }'Follow-up questions
- How would you sum %MEM per user?
- The OOM killer ended a process last night. Where do you confirm which one and why? (
dmesg -T,journalctl -k,oom_score)
Frequently asked questions
%MEM is resident memory (RSS) as a share of physical RAM, which is a fair first look. RSS counts shared libraries and shared memory in every process that maps them, so the numbers can add up to more than 100%, especially for PostgreSQL. For an exact per-process figure use PSS from smem or /proc/<pid>/smaps_rollup.