Chapter 7 · Lesson 4 of 11
Linux for servers

Linux processes and signals (ps, kill, SIGTERM, SIGKILL)

A process is a running program with a PID, and you control it by sending signals with kill: SIGTERM asks it to stop cleanly, SIGKILL forces it, and SIGHUP usually asks it to reload.

By the end you will

Find a process, stop it with the right signal, and tell when systemd will restart it so you stop the service instead of the process.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • An Ubuntu or Debian server you can reach over SSH
  • A user with sudo access

Something on your server is using all the CPU, or a stuck program will not let go of a port. To deal with it you need to find the process, pick the right way to stop it, and know whether a supervisor will start it again. The wrong move, such as kill -9 on a database, can corrupt data.

How it works#

Every running program is a process with a PID (process ID), an owner, and a parent. Process 1 is init, which on Ubuntu is systemd, and it is the ancestor of everything else.

Processes are controlled with signals, small messages the kernel delivers. A program can register a handler to react to most of them, for example to flush files before exiting. The signals you use:

  • SIGTERM (15): ask the program to terminate. It can clean up. This is the default for kill.
  • SIGKILL (9): the kernel ends the process immediately. It cannot be caught or ignored, so no cleanup runs.
  • SIGHUP (1): originally “terminal hung up”. Many daemons treat it as “reload your config”.
  • SIGINT (2): what Ctrl+C sends.
  • SIGSTOP and SIGCONT: pause and resume a process.

A daemon managed by systemd is different: systemd itself is the parent, and it can restart the process when it dies. That is why killing the process often does nothing useful.

Step 1: List and find processes#

bash
ps aux
ps aux --sort=-%mem | head
ps -ef --forest
pgrep -a nginx
pgrep -af "node server.js"

ps aux shows every process with its owner (USER), PID, CPU and memory percentages, state (STAT) and command. --sort=-%mem puts the biggest memory users first. ps -ef --forest draws the parent and child tree. pgrep -a name prints matching PIDs and command lines. -f matches the whole command line, which you need for scripts started as node server.js, because the process name is only node.

Avoid ps aux | grep name as your first choice, because it also matches the grep itself. pgrep does not.

For a live view, run top, or htop if you installed it with sudo apt install htop. In top, press M to sort by memory, P for CPU, k to send a signal to a PID, and q to quit. The STAT column is worth knowing: R running, S sleeping, D waiting on disk (cannot be killed until it returns), Z zombie, T stopped.

Step 2: Stop a process with kill#

bash
kill 2210
sleep 5
pgrep -a node
kill -9 2210

kill PID sends SIGTERM. Wait a few seconds, because a program may take time to close connections. Check with pgrep. Only if it is still there, send kill -9 PID. kill -9 risks leaving lock files, half-written data and unreleased ports, so it is the last resort.

To signal by name, use pkill name (SIGTERM) or pkill -f "node server.js". It matches every process with that name, so run pgrep -a name first and read the list. A process owned by another user needs sudo kill PID.

To ask for a reload:

bash
sudo kill -HUP "$(cat /run/nginx.pid)"

For a systemd service, use sudo systemctl reload nginx instead. It runs the right reload action for you.

Step 3: Stop a managed service the right way#

Check whether systemd owns the process:

bash
systemctl status myapp

Read Active:, Main PID: and the recent log lines. If the process is a service, stop and start it through systemd:

bash
sudo systemctl stop myapp
sudo systemctl restart myapp
sudo systemctl disable myapp

stop ends it now, restart stops then starts it, and disable stops it from starting at boot. If you kill the process directly and the unit has Restart=always or Restart=on-failure, systemd starts a new one after RestartSec. You will see a new PID in systemctl status. The full unit file story is in run a service with systemd. Docker has the same behavior with restart policies, see fix a Docker container that keeps restarting.

To see why a service died, read its log with journalctl -u myapp -n 50, covered in read logs with journalctl.

Step 4: Handle a stuck process#

When SIGTERM does nothing:

  1. Check the state with ps -o pid,stat,wchan:20,cmd -p PID. A D state means it is waiting on I/O and even SIGKILL will wait.
  2. Wait and retry. Many shutdowns take a few seconds, especially for apps that drain connections. See Node SIGTERM and graceful shutdown.
  3. Send kill -9 PID only if you accept the data risk.
  4. A zombie (Z) is already dead and waits for its parent to collect it. Killing it does nothing. Restart the parent.

Check it worked#

bash
pgrep -a myapp
systemctl is-active myapp
sudo ss -ltnp | grep 8080

An empty pgrep and inactive mean the process is gone and stays gone. If a new PID appears after a few seconds, a supervisor restarted it. If the port is still listed, another process holds it, see find what is using a port.

Edge cases and gotchas#

  • kill -9 skips cleanup. Databases, caches and file writers can lose data or leave lock files. Always try SIGTERM first.
  • PIDs are reused. A PID from an hour ago may now belong to something else. Check with ps -p PID before you kill.
  • A kill by name hits everything. pkill python ends every Python process you own, including ones you forgot. List first with pgrep -a.
  • Killing the shell’s job. A process started with & or nohup survives logout, but one started in a plain session may get SIGHUP when SSH drops. Use systemd or tmux for long jobs.
  • Containers have their own PID view. On the host, ps shows container processes too, but stop them with docker stop, which sends SIGTERM and then SIGKILL after a timeout.
  • sudo is needed for other users’ processes. kill: (1234): Operation not permitted means you do not own it.

Troubleshooting#

SymptomLikely causeFix
bash: kill: (1234) - Operation not permittedThe process belongs to another userUse sudo kill 1234
bash: kill: (1234) - No such processThe PID already exited or was reusedRun pgrep -a name again for the current PID
Process returns with a new PID after killsystemd or Docker restarts itsudo systemctl stop name or docker stop name
kill did nothing and the process is still runningThe program ignores or is slow to handle SIGTERMWait, check STAT, then kill -9 as a last step
Process shows STAT of D and will not dieStuck in uninterruptible I/O, often a dead disk or mountFix the I/O cause; reboot if needed
Z or <defunct> entries in psZombie whose parent never reaped itRestart or fix the parent process
pkill: killing pid 2210 failed: Operation not permittedNot your processRun with sudo
Failed to stop myapp.service: Unit myapp.service not loaded.Wrong unit nameList with systemctl list-units --type=service

Quick reference#

bash
ps aux --sort=-%mem | head    # top memory users
pgrep -a name                 # find PIDs
top                           # live view, q to quit
kill PID                      # SIGTERM, clean stop
kill -9 PID                   # SIGKILL, last resort
kill -HUP PID                 # ask for reload
pkill -f "pattern"            # signal by command line
systemctl status name         # state and main PID
sudo systemctl stop name      # stop a managed service

Next#

Processes run as users. See who owns what in users, groups and sudo.

Try it: Find a process and stop it cleanly

Find a stray process, ask it to stop with SIGTERM, then check how a managed service reports its state.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1Which signal does a plain kill 1234 send?
2Why can a program not ignore SIGKILL?
3A service comes back a few seconds after you kill its process. What should you run to stop it for good?
4What does pgrep -a nginx print?

Frequently asked questions

What is the difference between kill and kill -9?

kill sends SIGTERM, which lets a program clean up and exit. kill -9 sends SIGKILL, which the kernel enforces at once and the program cannot catch, so it may leave temp files, locks or half-written data.

How do I find the PID of a process in Linux?

Run pgrep -a name to list matching PIDs with their command lines, or ps aux | grep name. For a systemd service, systemctl status name shows the main PID.

Why does a process restart after I kill it?

Something supervises it, usually systemd with Restart=always or a Docker restart policy. Stop it through the supervisor, for example sudo systemctl stop name.

How do I reload a service config without restarting it?

Many daemons reload on SIGHUP, which systemctl reload name sends or runs the right command for. Check that the service supports reload before you rely on it.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios