Skip to content

Slow machine, busy port: top, ps and lsof

NinjaLesson 53 of 668 min

Your laptop is hot and your server won’t start because the port is taken. Use top and ps to find the CPU hog, lsof to find who holds the port, and kill both.

Two complaints at once: the laptop's fan won't stop, and the web server you want to start says the port is already in use. Both are processes you didn't know were there. Time to find them.

What is using the CPU: top and ps

top shows the busiest processes first and refreshes every few seconds. Press q to leave it. (Real top has more keys: M sorts by memory, k kills a process. The practice one only knows q.)

top

The columns that matter: PID (the number you'll kill it by), %CPU (100 is one whole core), %MEM, TIME+ (CPU time used so far) and COMMAND. top -b -n 1 prints one screen and exits, which is handy in scripts and pipes.

ps takes a snapshot instead. Sorted by CPU, with the full command line:

ps aux --sort=-%cpu | head -n 5

Who holds that port: lsof

Try starting a little web server for ~/site:

python3 -m http.server 8080

"Address already in use". Something listens on 8080 already. lsof (list open files) knows, because on Linux a network socket is a kind of open file:

lsof -i :8080

lsof -t -i :8080 prints only the PID, which you can hand straight to kill: kill $(lsof -t -i :8080). ss -tlnp answers the same question from the network side.

Stopping a process

kill PID asks a process to stop (the TERM signal), and a well-behaved program tidies up and exits. pkill name does the same by name. Check with ps or top that it's really gone.

Your turn

Find the process that is using a whole CPU and stop it. Then find what holds port 8080, stop it, and start your own server with python3 -m http.server 8080 & from ~/site.

Next