Introduction: Why Manage Processes?
Every running program in Linux is a process. Managing them is one of the key tasks for a system administrator and developer. Do you need to:
- Find and terminate a "hung" process that's eating up all memory?
- Find out which specific process is listening on a network port?
- Run a task in the background to close the terminal?
- Configure auto-start for an important service?
This guide covers everything—from basic commands like ps and kill to the modern system service manager systemd. You'll gain practical skills you'll use daily.
Basic Monitoring: ps, top, and htop
The ps Command — A Process Snapshot
ps (process status) shows a static list of processes at the moment the command is run.
Most useful options:
# Show all processes for all users in "full" format (BSD-style)
ps aux
Key columns:
USER— process owner.PID— unique process identifier (the main thing needed for management).%CPU,%MEM— CPU time and memory consumption.COMMAND— the command that started the process.
# Alternative, more detailed format (POSIX-style)
ps -ef
Here the columns are: UID, PID, PPID (parent's PID), C (CPU usage coefficient), STIME (start time), CMD.
Filtering: Always combine ps with grep for searching.
ps aux | grep nginx
ps -ef | grep python3
⚠️ Important:
grepitself will appear in the output. Usepgrepfor clean name searching:pgrep -l nginx.
top and htop — Interactive Monitoring
top — the classic utility that updates the process list in real-time (by default every 3 seconds).
Main keys in top:
P— sort by CPU load (default).M— sort by memory usage.N— sort by PID.k— kill a process (will ask for PID and signal).r— change (renice) a process's priority.u— show processes only for a specified user.q— quit.
htop — a more convenient and visually clear color alternative to top. It's often not installed by default, but it's worth installing (sudo apt install htop / sudo yum install htop). Allows managing processes directly from the interface (F9 for kill, F5 for tree, F6 for sorting).
Finding Processes: Not Just by Name
Sometimes you need to find a process not by its name, but by other attributes.
By Open Port or Socket
A common task: "Who is listening on port 80?".
# Recommended modern method (from iproute2 package)
sudo ss -tulpn | grep :80
Options: -t (TCP), -u (UDP), -l (only listening), -p (show process/program).
# Classic method (from net-tools package)
sudo lsof -i :80
lsof (list open files) shows all open files, including network sockets. A very powerful tool.
By File or Directory
Which process has /var/log/app.log open and prevents you from deleting it?
sudo lsof /var/log/app.log
By Process Tree
To see the hierarchy (parent and child processes), use:
pstree -p
Or in htop press F5.
Terminating Processes: kill, killall, pkill
Signals: The Language of Talking to Processes
Termination isn't just a "shot". It's sending a signal—a short message to the process. The main ones:
| Signal | Number | Default Action | How to Use |
|---|---|---|---|
SIGTERM | 15 | Graceful termination. The process can handle the signal, save state, and shut down cleanly. | kill <PID> (this signal is sent by default) |
SIGKILL | 9 | Immediate forced termination. Signal handler is ignored. Process cannot save data. | kill -9 <PID> or kill -KILL <PID> |
SIGINT | 2 | Interrupt (like Ctrl+C in the terminal). | kill -2 <PID> |
SIGHUP | 1 | "Hang up". Often used to reload configuration files without a full restart. | kill -HUP <PID> |
Rule: First try SIGTERM (just kill). If the process doesn't respond (hangs), use SIGKILL.
Tools
kill <PID>— sendSIGTERMto a specific PID.kill -s SIGNAL <PID>orkill -SIGNAL <PID>— send a specific signal. Example:kill -HUP 1234.killall <process_name>— terminate all processes with the given name.killall nginx. Caution! Make sure you're killing what you intend.pkill <pattern>— terminate processes matching a pattern (by name, user, etc.).pkill -f "python3 script.py"(searches in full command line). Powerful, but requires care.pgrep <pattern>— only find PIDs by pattern. Perfect for combination:kill $(pgrep -f "python3 script.py").
Managing Priorities: nice and renice
The Linux scheduler distributes CPU time among processes. You can influence priority.
nice— starts a process with a specified static priority.- Range: from
-20(highest priority, requiressudo) to+19(lowest). - Example of starting with low priority (so it doesn't interfere with other tasks):
nice -n 19 ./long_running_task.sh - If you don't specify
-n,+10is used by default.
- Range: from
renice— changes the priority of an already running process.# Increase priority (decrease nice value) for PID 5678 sudo renice -5 -p 5678
💡 Tip: Don't raise (
nice < 0) the priority of important system processes unnecessarily. This can cause "starvation" of other tasks.
Background Processes and Job Control
Simple Background Execution
Add & to the end of the command:
long_running_command &
[1] 2345 # [1] - job number, 2345 - PID
The command returns control to the terminal immediately.
Job Control
jobs— show list of background jobs in the current shell.fg %1— bring job #1 to the foreground.bg %1— resume stopped job #1 in the background.Ctrl+Z— suspend (stop) the current foreground process (does not terminate it!).
Independence from Terminal: nohup and disown
By default, a background process (&) is still "attached" to the terminal. If the terminal closes (e.g., SSH connection drops), the process will receive a SIGHUP signal and will likely terminate.
nohup(no hang up) — runs a process that ignores theSIGHUPsignal.
Output is redirected tonohup ./my_server.py > server.log 2>&1 &server.log.disown— after starting a process in the background (command &), you can "detach" it from the current shell:disown %1. After this, the process won't receiveSIGHUPwhen the terminal closes.
Modern Approach: systemd and systemctl
For long-running system services (web servers, databases, daemons) in modern distributions (Ubuntu 15.04+, CentOS 7+, Debian 8+), systemd is used.
Basic systemctl Commands
# Service status (running, PID, recent logs)
sudo systemctl status nginx
# Start/stop/restart
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx # soft restart (may briefly disconnect)
sudo systemctl reload nginx # reload config without stopping (if supported)
# Enable/disable auto-start on boot
sudo systemctl enable nginx
sudo systemctl disable nginx
# View all units (services, timers, sockets)
systemctl list-units --type=service --all
# View service logs (like journalctl)
sudo journalctl -u nginx -f # -f — follow in real-time
Creating Your Own Service
- Create a configuration file:
sudo nano /etc/systemd/system/myapp.service - Basic template:
[Unit] Description=My Custom Service After=network.target [Service] Type=simple ExecStart=/usr/bin/python3 /opt/myapp/main.py Restart=on-failure User=appuser WorkingDirectory=/opt/myapp [Install] WantedBy=multi-user.target - Activate:
sudo systemctl daemon-reload && sudo systemctl enable --now myapp.service.
Advanced Monitoring and Analysis
strace — System Call Tracing
If you need to understand exactly what a "hung" process is doing, use strace. It shows all the process's interactions with the kernel (reading/writing files, network requests, etc.).
# Trace an already running process
sudo strace -p <PID> -o trace.log
# Run a command under strace
sudo strace -o trace.log ./my_program
Use -c for statistics on system calls, -f to follow child processes.
lsof — "What's Open?"
Already mentioned, but worth highlighting separately. It's a Swiss Army knife for analysis.
# All open files for a specific PID
sudo lsof -p <PID>
# All network connections (like netstat)
sudo lsof -i
# Who is holding directory /mnt/backup (e.g., for unmount)
sudo lsof +D /mnt/backup
vmstat and iostat — Overall System Load
To understand if the problem is with a process or the system as a whole:
# Processes, memory, swap, I/O, CPU (updates every 2 sec)
vmstat 2
# Disk I/O statistics
iostat -xz 2
If vmstat shows high wa (I/O wait) — the problem is with disks. If high us/sy (user/system CPU) — the problem is with processes.
Conclusion and Best Practices
- Start with
ps auxortop/htopfor a general overview. - Use
grep/pgrep/pkillfor searching, but check output beforekillall. - Send
SIGTERM(kill) first,SIGKILL(-9) only as a last resort. - For services, use
systemctl, not manual startup with&. This provides auto-restart, logging, and management. nohupanddisownare your friends for long tasks in unstable SSH sessions.straceandlsofare powerful debugging tools for deep analysis.- Permissions: Managing other users' processes (especially via
killorrenice) often requiressudoprivileges.
Process management is a skill honed by practice. Experiment in a test environment, create "toy" hung processes (sleep 1000 &), and practice commands on them.