16 min read
Linux and Mac processes: ps, kill and signals
In one sentence: A process is a running program, and the system gives it a number, the PID. With ps and top you find it, with kill you send it signals like the one from Ctrl+C to stop it, and with lsof you find out which one holds a port.
What you will learn
- Explain what a process is and find its PID with ps, pgrep and top.
- Stop a process with Ctrl+C or with kill, and know when to use SIGTERM and when SIGKILL.
- Send a program to the background and bring it back with &, jobs, fg and bg, and keep it alive after closing the terminal with nohup.
- Find out which process is listening on a port and stop it.
Before you start, read: 04-users-and-permissions.md
The problem
Section titled “The problem”Imagine that yesterday you left a test server running in some terminal window. Today you start it again and it replies that port 8080 is already in use, but you can’t see any window to close. Who’s holding the port, and how do you stop it?
On a server this happens every day: a program eats up the CPU (the processor), you have to restart the website without cutting off anyone who’s in the middle of buying something, or you launch a long task, close the terminal and, when you come back, it’s gone.
All of those are processes: running programs. Here you learn to see them, to talk to them with signals and to stop them without breaking anything.
The analogy
Section titled “The analogy”The analogy
Think of a restaurant kitchen. A recipe written in a book doesn’t cook anything: it’s a program, a file sitting still on the disk. When a cook starts making it, that’s a process: the recipe in action. Three cooks can make the same recipe at once, and each dish carries its order number: that number is the PID.
The head chef stays away from the stove and passes short notes. “Stop what you’re doing.” “Finish when you can and clean up your station.” Those notes are the signals. And if someone doesn’t listen, the head chef calls security, who takes them out of the kitchen on the spot, with no time to turn off the burner.
Where the analogy breaks down
- The notes don’t carry free text: a signal is just a number from a fixed list.
- A process can ignore the “finish” note and keep its station. That’s why there’s a signal that can’t be ignored: the security one.
- When a process is forced out, the operating system does clean up part of its station: it closes its files and frees its port. What’s lost is whatever it had half done.
How it really works
Section titled “How it really works”A running program is a process
Section titled “A running program is a process”Open the terminal and type this:
echo $$psThe first command prints a number, for example 75474: the shell replaces $$ with its own number. The second, ps (for process status), shows it in a list next to -zsh (or bash, on Linux). Your shell is a running program.
A program is a file on the disk, like /bin/sleep. A ProcessA running program. When you start a server, the operating system creates a process that stays alive waiting for requests.Go to definition is a copy of that program in action, with its own memory and its own current folder (that’s why cd is part of the shell, as you saw in lesson 1). Three terminal windows are three zsh processes: the same program, three times.
The operating system gives each process a number, its PIDPID stands for Process Identifier.The number the operating system uses to identify each process while it’s running. It lets you address a specific process, for example to stop it.Go to definition, which is what you use to address it. PIDs are handed out in order and reused: today’s sleep won’t have the same number tomorrow.
Each process also has a parent, the one that started it: when you type sleep 60, the parent of sleep is your shell. If you climb up the family tree, you reach PID 1, the first one the system starts: launchd on the Mac and, on almost every Linux, systemd, which you’ll see in lesson 6.
Seeing processes: ps, pgrep and top
Section titled “Seeing processes: ps, pgrep and top”With no options, ps shows few processes: on the Mac, yours that have a terminal; on Linux, only the ones in this window. To see them all, from every user, you use ps aux (no dash: an old ps habit). That’s hundreds of lines, so you filter them with grep, as in lesson 3: ps aux | grep nginx looks for the nginx web server.
The columns you’ll look at the most:
| Column | What it says |
|---|---|
USER |
The user who owns the process |
PID |
Its number |
%CPU and %MEM |
How much processor and how much memory it uses |
STAT |
Its state: R is working, S is waiting for something (the normal case), T is paused |
COMMAND |
The command that started it |
If you know the name, pgrep gives you the PIDs directly: pgrep sleep prints the PID of every process whose name contains sleep. Containing it is enough (on the Mac, pgrep nc also finds launchservicesd), so -l, which also prints the name, is a good idea. And -f searches the full command: pgrep -fl "sleep 600".
top is the live version: a table that refreshes every second, with the processes that use the most at the top. You quit with Q. On Linux it sorts by CPU; on the Mac, by PID, and you have to ask for it with top -o cpu (-o for order).
Signals: messages for a process
Section titled “Signals: messages for a process”To stop a process, you send it a SignalA short notice the operating system delivers to a process, like “interrupt yourself” or “finish”. Each signal is a number with a name, like SIGTERM, and pressing Ctrl+C in the terminal sends one.Go to definition with kill and its PID:
kill 78026The name is misleading: kill doesn’t kill anything by itself. It asks the operating system to deliver a signal to that process: a short message, a number with a name that starts with SIG (for signal). The process receives it in the middle of whatever it’s doing and reacts.
There are more than thirty (kill -l lists them), but day to day you’ll use four, with the same numbers on the Mac and on Linux:
| Signal | Number | Who sends it | What it asks | Can it be ignored? |
|---|---|---|---|---|
SIGINT (interrupt) |
2 | Ctrl + C | Stop what you’re doing | Yes |
SIGTERM (terminate) |
15 | kill, with no options |
Finish, cleaning up first | Yes |
SIGKILL |
9 | kill -9 |
Nothing: the system stops it | No |
SIGHUP (hang up) |
1 | Closing the terminal | “Your terminal is gone” | Yes |
Ctrl + C isn’t sent by the shell: the terminal sees that key combination and sends SIGINT to the program in front of you, whatever it is.
With kill you choose the signal by its name, without the SIG, or by its number: kill -INT 78026 is the same as pressing Ctrl + C in its window, and kill -9 78026 is kill -KILL 78026.
Two limits:
- You can only send signals to your own processes. With other users’ processes,
killrepliesoperation not permitted. The root user can do it with all of them, as you saw in lesson 4. - Each program decides what to do with each signal, except with
SIGKILL. That’s why some programs don’t stop with Ctrl + C, like themanpager: they catch the signal and wait for you to quit with Q.
Ending cleanly or ending now: SIGTERM and SIGKILL
Section titled “Ending cleanly or ending now: SIGTERM and SIGKILL”kill sends SIGTERM by default for a good reason: the program can catch it and end cleanly. A web server that receives SIGTERM stops accepting new requests, finishes the ones it has in progress, closes its connection to the database and exits. This is called a graceful shutdown.
SIGKILL doesn’t even reach the program: the operating system removes it on the spot.
- Web serverFinishes the requests,
closes connections and exits - Operating system · Web serverSIGKILL doesn't reach the server:
the system stops it on the spot
With SIGKILL, the purchase that was half done gets cut off, and a file can be left half written. On the other hand, the operating system closes the process’s SocketWhat the operating system gives a program to use the network, with its protocol, IP address and port. A server listens with a socket, and each conversation has a socket at each end, which also knows the other end’s IP address and port.Go to definition, so its PortA number, from 0 to 65535, that says which program on a computer a connection is for. The computer has an address; each listening program has its port.Go to definition is freed.
The rule: first kill, wait a few seconds and, only if it’s still alive, kill -9. docker stop (Phase 7) does exactly that: it sends SIGTERM, waits ten seconds by default and, if the program is still there, SIGKILL.
When a process ends because of a signal, its Exit codeThe number a program leaves when it finishes. 0 means it went well, and any other, from 1 to 255, that something failed. The shell keeps it in $?, and scripts check it to decide whether to go on.Go to definition (the $? from lesson 3) is 128 plus the signal’s number: 130 after Ctrl + C, 143 with SIGTERM and 137 with SIGKILL.
Foreground and background
Section titled “Foreground and background”When you type sleep 60, the terminal waits, because sleep is in the foreground: it receives what you type, and you don’t get the prompt back until it ends.
If you add & at the end, it starts in the background: it keeps running and the shell gives you the prompt back right away, with two numbers, like [1] 78026. The 1 is the job number, which only exists in this window, and 78026 is the PID.
To manage a window’s jobs:
| What you want | How |
|---|---|
| Start a program in the background | command & |
| See this window’s jobs | jobs |
| Bring a job to the foreground | fg (the last one) or fg %2 (number 2) |
| Pause the one in the foreground | Ctrl + Z |
| Resume a paused one in the background | bg |
| Stop it by its job number | kill %1 |
Ctrl + Z also sends a signal, SIGTSTP (for terminal stop), which pauses the process without ending it: it stays in memory with everything it had open, its port included. fg and bg wake it up.
When you close the terminal: SIGHUP and nohup
Section titled “When you close the terminal: SIGHUP and nohup”When you close a terminal window, its shell receives SIGHUP and passes it on to its jobs: whatever you left in the background dies with the window. The name comes from the days when terminals connected over the phone.
For a process to survive, launch it with nohup (no hang up) in front: nohup command &. nohup makes the program ignore SIGHUP and saves whatever it writes in a file, nohup.out, because once the window is closed there will be no terminal to write to.
On a server, nohup is a stopgap: if the program fails or the server restarts, nobody starts it again. That’s what systemd services are for, in lesson 6.
Some programs without a terminal, like nginx, give SIGHUP another meaning: “read your configuration again.” That way you change it without stopping them.
Which process is listening on a port
Section titled “Which process is listening on a port”In lesson 5 of Phase 0 you used lsof to see which programs are listening. Now it gives you the PID of the one holding a port:
lsof -nP -iTCP:8080 -sTCP:LISTENIt asks for the TCP sockets on port 8080 that are listening, with addresses and ports as numbers (-n and -P). The PID column has the number for kill. If it prints nothing, nobody is listening on that port.
Two details:
- Without
sudo,lsofonly shows your processes. A system nginx, which belongs to another user, wouldn’t show up. On your practice server,sudo lsof -nP -iTCP:80 -sTCP:LISTENshows everything. - On Linux, it may not come installed. On Ubuntu you install it with
sudo apt install lsof.
Try it
Section titled “Try it”The goal: find and stop a server without knowing which window you started it in. Everything happens in your terminal, in the practice folder (cd ~/backend-course/phase-1), and the only thing created is an empty file, which you’ll delete at the end.
The outputs come from a Mac with zsh. Your numbers will be different, and each exercise says what changes on Linux and in WSL, with bash.
1. Your shell is a process too
echo $$psWhat you will see:
75474PID TTY TIME CMD75474 ttys015 0:00.02 -zsh75479 ttys016 0:00.02 -zshNotice that 75474 shows up in the list. On the Mac, ps shows your processes from every window, and TTY says which one each belongs to. The dash in -zsh marks the shell the window was opened with. On Linux and WSL only the ones in this window show up: bash and ps itself.
2. Stop the one in front with Ctrl+C
sleep 60What you will see:
^Csleep 60 waits 60 seconds doing nothing, in the foreground. Press Ctrl + C. The terminal prints ^C, sends SIGINT to sleep and the prompt comes back.
Now type echo $?. It replies 130: 128 plus the 2 of SIGINT. It’s the same on Linux.
3. To the background
sleep 300 &jobspsWhat you will see:
[1] 78026[1] + running sleep 300PID TTY TIME CMD75474 ttys015 0:00.03 -zsh78026 ttys015 0:00.00 sleep 30075479 ttys016 0:00.02 -zshYou can paste the three commands together: with &, the shell doesn’t wait. jobs says job 1 is running, and ps shows sleep with the PID that [1] 78026 gave you.
On Linux and WSL, jobs prints [1]+ Running sleep 300 &, and ps shows just sleep, without the 300.
4. Pause, resume and stop
fgbgkill 78026What you will see:
[1] + running sleep 300^Zzsh: suspended sleep 300[1] + continued sleep 300[1] + terminated sleep 300This time, type the commands one at a time:
fgbringssleepto the foreground: the terminal waits again.- Press Ctrl + Z. zsh says
suspended: the process is paused, not ended. bgresumes it in the background (continued) and gives you the prompt back.kill, with the PID from exercise 3, sends itSIGTERM. zsh reportsterminated(withkill -9it would bekilled); if it doesn’t show up right away, press Enter.
If kill replies no such process, that PID isn’t yours: jobs -l shows it to you.
On Linux and WSL, bash prints sleep 300 on fg, [1]+ Stopped when you pause it, [1]+ sleep 300 & when you resume it and [1]+ Terminated when you stop it.
Now, a process that really uses the CPU. yes prints the letter y nonstop, and > /dev/null throws away everything it writes, so all it does is keep the processor busy.
5. Who's eating the CPU?
yes > /dev/null &top -o cpuWhat you will see:
Processes: 521 total, 7 running, 514 sleeping, 3089 threads 14:58:11Load Avg: 12.22, 8.13, 6.42 CPU usage: 42.64% user, 42.53% sys, 14.81% idle…PID COMMAND %CPU TIME #TH #WQ #PORT MEM PURG CMPRS PGRP PPID STATE47458 yes 91.0 00:11.96 1/1 0 11 816K 0B 0B 47458 45645 running0 kernel_task 9.9 04:11:54 821/8 0 0 13M+ 0B 0B 0 0 running47670 top 8.5 00:01.14 1/1 0 46+ 6256K 0B 0B 47670 45645 running394 WindowServer 7.8 04:17:39 21 4 2872+ 445M- 5840K+ 128M 394 1 sleeping…The processes are sorted by %CPU, and yes comes first, close to 100%: a whole processor core. Look at PPID (parent PID): yes and top have the same one, 45645, your shell. We’ve removed lines from other programs; yours will be different.
Quit with Q and stop yes with kill %1: zsh replies [1] + terminated yes > /dev/null.
On Linux and WSL, type just top, which already sorts by CPU: yes shows up with an R in the S column (for state) and 100.0 in %CPU.
Now, a process that outlives its window:
6. Survive closing the window
nohup sleep 600 &What you will see:
[1] 95202appending output to nohup.outnohup warns that it will save whatever the program writes in nohup.out, in this folder. With sleep it will stay empty.
Now close the whole window. If the terminal asks whether you want to end its processes, accept: sleep will ignore the SIGHUP.
On Linux and WSL, the warning is nohup: ignoring input and appending output to 'nohup.out'.
Open a new window and look for it:
7. Find it from another window
pgrep -f "sleep 600"ps -p 95202What you will see:
95202PID TTY TIME CMD95202 ?? 0:00.01 sleep 600pgrep -f finds it by its full command. Replace the 95202 in ps -p (-p for process) with yours: it’s still alive, and its TTY is ??, because it no longer belongs to any terminal.
jobs wouldn’t show it: jobs belong to the window that launched them, which no longer exists. Stop it with kill and your PID, and delete the empty file with rm ~/backend-course/phase-1/nohup.out. If you repeat the test without nohup, pgrep finds nothing: the process died with the window.
On Linux and WSL, TTY is ? and CMD is just sleep.
And now, the ghost server. Open a window, start nc -l 8080, as in Phase 0, and forget about it. From another one, find who’s holding port 8080 and stop it:
8. Who's holding port 8080?
lsof -nP -iTCP:8080 -sTCP:LISTENWhat you will see:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEnc 86565 ana 3u IPv4 0x959f2d62bde58997 0t0 TCP *:8080 (LISTEN)It’s held by nc, with PID 86565. Stop it with kill and your number. In the nc window, zsh: terminated nc -l 8080 appears (in bash, Terminated) and the prompt comes back. Repeat the lsof: it no longer prints anything.
We’ve changed the username to ana. If lsof prints nothing from the start, check that nc is still waiting in the other window. On Linux and WSL, the output is almost the same.
You have already seen it
Section titled “You have already seen it”- Ctrl + C has been your way of stopping
nc,curlortraceroutesince Phase 0: it wasSIGINT. - The Mac’s Activity Monitor (or the Windows Task Manager) is a
topwith windows. Its “Force Quit” is likekill -9: the program gets no chance to save anything. - When you close a terminal window with something running, many terminals ask you to confirm: that something will die from the
SIGHUP.
And if you code:
npm run devstops with Ctrl + C. For your Node server to end cleanly, you catch the signal withprocess.on('SIGTERM', …), close the server and exit.Error: listen EADDRINUSE: address already in use :::3000is the ghost server:lsof -nP -iTCP:3000 -sTCP:LISTENgives you the PID you have to stop.- “Exited with code 137” in Docker or in a cloud service is 128 + 9: the process ended with
SIGKILL, often because it ran out of memory and the system stopped it.
Common mistakes
Section titled “Common mistakes”- Using
kill -9right away. It works, but whatever the program had half done is lost. Trykillfirst and use-9only if it’s still alive a few seconds later. - Pressing Ctrl + Z to quit a program. It only pauses it, and the process keeps holding its memory and its port. If, when you exit, zsh says
you have suspended jobs.or bash saysThere are stopped jobs., that’s why: go back withfgand quit with Ctrl + C. - Believing
ps aux | grep nginxfound something. The list almost always includesgrepitself, which is running while it searches: the line that ends ingrep nginxis your search, not nginx.pgrep nginxdoesn’t have that problem. - Mixing up the job number and the PID.
kill 1tries to stop PID 1, the one that starts the system; since it isn’t yours, it replieskill: kill 1 failed: operation not permitted(in bash,bash: kill: (1) - Operation not permitted). You meantkill %1.
Summary
Section titled “Summary”- A process is a running program, and the PID is its number.
ps,pgrepandtoptell you which ones there are and how much they use. - A signal is a message the system delivers to a process. Ctrl + C sends
SIGINT;kill,SIGTERM;kill -9,SIGKILL; and closing the terminal,SIGHUP. SIGTERMlets the program end cleanly;SIGKILLstops it on the spot. First one, and the other only if needed.&launches in the background,jobslists the jobs,fgandbgmove them and Ctrl + Z pauses.nohupmakes a process survive the terminal closing.lsof -nP -iTCP:PORT -sTCP:LISTENgives you the PID of the process listening on a port.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- The Linux Command Line, by William Shotts: its chapter 10, “Processes,” adds commands like
pstreeandkillall. - signal(7): every Linux signal, with its number and its default action.
- Job control in the bash manual:
&,jobs,fg,bgand the%.