Slow machine, busy port: top, ps and lsof
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.)
topThe 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 5Who 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 :8080lsof -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.
Your task
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.
- The CPU hog is stopped (not done yet)
- Port 8080 is free of the old server (not done yet)
- Your server listens on 8080 (not done yet)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
top- Show the busiest processes More on top
ps aux- Every process, with user, %CPU, %MEM, start time and command More on ps
lsof -i- Network sockets, or the ones on this port (-i tcp:22 too) More on lsof
kill- Send a signal to a process (usually: stop it) More on kill
Every everyday command on one page: the Linux commands cheat sheet.