How Linux Handles Memory, Processes, and CPU Resources
Objective
When a Linux system feels slow, the cause is nearly always a shortage of one of three things: CPU time, memory, or both. Fixing it quickly requires understanding what the kernel is actually doing with them. This guide explains how Linux manages processes, CPU scheduling, and memory, then shows how to monitor and troubleshoot each one. By the end, you will know how to:
- Explain what a process is, how it is created, and what its states mean
- Describe how the scheduler shares CPU time, and how nice values influence it
- Explain virtual memory, paging, swap, the page cache, and the out-of-memory killer
- Read the output of
top,ps,free,vmstat, anduptimecorrectly - Diagnose a slow system step by step
- Manage misbehaving processes with signals,
nice, andrenice
The Kernel as Resource Manager
Right now your computer may be running a browser, a terminal, an editor, and dozens of background services. All of them want the CPU, memory, storage, and network at the same time. The Linux kernel sits between those programs and the hardware and decides who gets what, and when. Without it, one badly behaved program could take over the whole machine.
Three mechanisms do most of this work, and they run continuously in the background:
| Area | What It Decides | Key Commands |
|---|---|---|
| Process management | Which programs are running, how they relate to each other, and what state each one is in | ps, pstree, top, kill |
| CPU scheduling | Which runnable process gets CPU time next, and for how long | nice, renice, chrt, uptime |
| Memory management | How RAM and swap are allocated, shared, and reclaimed | free, vmstat, swapon --show |
Processes: Programs in Motion
A program is a set of instructions stored on disk. When you start it, Linux creates a process: the running instance, with its own memory, open files, and state. Every process has a unique number called a process ID (PID) that Linux uses to track and manage it.
# Processes in the current terminal
ps
# Every process on the system, with owner, CPU, and memory
ps aux
# A custom view: PID, parent PID, state, nice value, CPU, memory, command
ps -eo pid,ppid,stat,ni,%cpu,%mem,cmd --sort=-%cpu | head -10
# Live view of processes
top
# The family tree of processes, with PIDs
pstree -p
Parents and Children
Every process except the first has a parent that created it. The first process, PID 1, is started by the kernel and on modern systems is systemd. Everything else descends from it, which is why pstree shows a single tree.
Creating a new process uses two steps, which is why you will see both names in documentation:
- fork: the parent creates a copy of itself, the child
- exec: the child replaces its own program with a different one
In shorthand: parent process, fork, child process, exec, new program. Whenever you type a command in a shell, the shell forks a child and the child execs your command.
Process States
A process is not always running. The scheduler tracks its state, and the STAT column in ps shows it:
| State | Letter | Meaning | Worth Worrying About? |
|---|---|---|---|
| Running or runnable | R |
Using the CPU, or ready and waiting for a turn | Many at once means CPU contention |
| Sleeping (interruptible) | S |
Waiting for an event such as input or a timer | No, this is the normal state for most processes |
| Uninterruptible sleep | D |
Waiting on I/O, usually disk or network storage, and cannot be interrupted | Yes if many, or if it persists. It points to a storage problem. |
| Stopped | T |
Paused by a signal or a debugger | Only if you did not expect it |
| Zombie | Z |
Finished, but the parent has not collected its exit status | A few are harmless. Many point to a buggy parent. |
Zombies and Orphans
When a process ends, the kernel frees its memory and other resources, but keeps a small entry so the parent can read its exit status. Until the parent does, the process shows as a zombie. A zombie uses no CPU and almost no memory, but it holds a PID.
- You cannot kill a zombie. It is already dead, so
kill -9does nothing. The fix is for the parent to collect it, or you terminate the parent so thatsystemdadopts and clears the zombie. - A child whose parent exits first is called an orphan. Linux hands it to PID 1 so it is not left without a parent.
# Find zombie processes and their parents
ps -eo pid,ppid,stat,cmd | awk '$3 ~ /^Z/'
# Find processes stuck in uninterruptible sleep, and what they are waiting on
ps -eo pid,stat,wchan:20,cmd | awk '$2 ~ /^D/'
CPU Scheduling
A computer with four CPU cores can truly run only four things at any one instant, yet hundreds of processes exist. The scheduler solves this by giving each runnable process short slices of CPU time and switching between them thousands of times a second, fast enough that everything appears to run at once. On multi-core systems it also spreads runnable tasks across cores so that work genuinely runs in parallel.
A small point of history helps when reading older articles. For many years the default scheduler for ordinary processes was called CFS (the Completely Fair Scheduler). Since Linux 6.6 it has been replaced by a newer design called EEVDF. The commands you use do not change, but the name you will see in documentation does.
Scheduling Policies
| Policy | Used For | Notes |
|---|---|---|
SCHED_OTHER (normal) |
Ordinary processes, which is nearly everything | Influenced by nice values |
SCHED_BATCH |
CPU-heavy background work | Tuned for throughput over responsiveness |
SCHED_IDLE |
Work that should run only when nothing else needs the CPU | Lowest priority of all |
SCHED_FIFO and SCHED_RR |
Real-time tasks with strict timing needs | Run ahead of all normal processes. A runaway real-time task can starve the whole system. |
SCHED_DEADLINE |
Real-time tasks defined by deadlines | Advanced and rarely needed outside specialized workloads |
Nice Values: Adjusting Priority for Normal Processes
For ordinary processes, the lever you use is the nice value. It ranges from -20 to 19. A higher value means the process is nicer to others, so it gets a smaller share of the CPU when there is contention. A lower value means a larger share. The default is 0.
- Any user can raise the nice value of their own processes, making them less demanding
- Only root can lower a nice value below the current one, which gives a process more priority
- Nice values only matter when processes are competing. On an idle CPU, a nice 19 process still runs at full speed.
# Start a command with a higher nice value (lower priority)
nice -n 10 tar -czf /tmp/backup.tar.gz /home
# Change the nice value of a running process by PID
renice -n 5 -p 1234
# Lower the nice value (higher priority), root only
sudo renice -n -5 -p 1234
# Show nice values (NI) next to each process
ps -eo pid,ni,cmd --sort=-ni | head
# Inspect or set the scheduling policy of a process
chrt -p 1234
# Set a command to run only when the CPU is otherwise idle
chrt --idle 0 ./long-job.sh
Two cautions. First, the older form renice 10 -p 1234 still appears in tutorials, but renice -n 10 -p 1234 is clearer and is the form to use. Second, nice values influence CPU only. A process that is slowing the system by hammering the disk needs ionice instead, for example ionice -c 3 command to run it with idle I/O priority.
Be very careful with real-time policies. Setting a busy task to SCHED_FIFO at a high priority can leave ordinary processes, including your shell, unable to get any CPU time.
Memory Management
Virtual Memory
Linux does not hand each program a slice of physical RAM. Instead, each process gets its own virtual address space, and the kernel, with help from the CPU hardware, maps those virtual addresses to physical memory. The program believes it has a large, private block of memory, and it never needs to know where the data really lives.
Memory is managed in fixed-size units called pages, commonly 4 KiB, and page tables record which virtual page maps to which physical page.
| Benefit | Why It Matters |
|---|---|
| Isolation | One process cannot read or overwrite another process's memory, which is a major reason a crashing program does not usually take the system with it |
| Simplicity for programs | Applications use virtual addresses and do not manage physical RAM themselves |
| Sharing | Shared libraries can be loaded into physical memory once and mapped into many processes |
| Flexibility | Pages can be loaded on demand, moved to swap, or reclaimed when needed |
| Overcommit | The kernel can allow processes to reserve more virtual memory than physically exists, betting that not all of it will be used at once |
The Page Cache: Why "Free" Memory Looks Low
This is the single most misunderstood part of Linux memory. Unused RAM is wasted RAM, so Linux uses spare memory as a cache for files it has read from disk. Repeated reads are then served from memory instead of the disk, which is far faster. When an application needs that memory, the kernel releases cache pages instantly.
The result is that a healthy Linux system often shows very little "free" memory, and that is normal. The number to watch is available.
free -h
# Sample output:
# total used free shared buff/cache available
# Mem: 7.7Gi 2.1Gi 1.2Gi 110Mi 4.4Gi 5.3Gi
# Swap: 2.0Gi 0B 2.0Gi
| Column | Meaning |
|---|---|
total |
Installed physical memory |
used |
Memory in use by processes and the kernel |
free |
Memory not being used for anything at all. A small number here is normal. |
shared |
Memory shared between processes, such as tmpfs contents |
buff/cache |
Memory holding file data and buffers. It can be reclaimed when needed. |
available |
An estimate of how much memory can be given to new applications without swapping. This is the useful number. |
Swap and Memory Pressure
When physical RAM runs low, the kernel can move memory pages that have not been used recently to swap, an area on disk, freeing RAM for work that needs it now. That is useful, but disk is far slower than memory, so swap is a safety valve and not a substitute for RAM.
- A little swap use is normal. The kernel may move rarely used pages out even when RAM is not full, to make more room for cache.
- Constant swapping is a problem. If pages are repeatedly moved out and back in, the system spends its time waiting on disk, and everything slows down. This is often called thrashing.
- The tendency to swap is tunable. The
vm.swappinesssetting (default 60) controls how readily the kernel swaps. Lower values make it prefer keeping memory pages in RAM.
# Show active swap areas and how much is used
swapon --show
# Check the current swappiness setting
sysctl vm.swappiness
# Change it for the running system
sudo sysctl vm.swappiness=20
# Make it persistent across reboots
echo "vm.swappiness=20" | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system
# Detailed memory counters straight from the kernel
head -20 /proc/meminfo
The Out-of-Memory Killer
If memory and swap are both exhausted and the kernel cannot reclaim enough, it has a last resort: the OOM killer. It picks a process, scoring it mainly by how much memory it uses, and terminates it to keep the system alive. When a service vanishes without an obvious reason, this is a common cause.
# Look for OOM killer activity in the kernel log
journalctl -k | grep -i -E "out of memory|oom"
dmesg -T | grep -i -E "out of memory|killed process"
# See how likely a process is to be chosen (higher means more likely)
cat /proc/1234/oom_score
# Make a critical process less likely to be killed (root only)
echo -500 | sudo tee /proc/1234/oom_score_adj
Also note that on systemd systems, control groups can cap what a service or container may use, so a process can be killed for exceeding its own limit long before the whole machine runs out of memory:
# Run a command in a transient scope with a memory and CPU limit
sudo systemd-run --scope -p MemoryMax=500M -p CPUQuota=50% ./heavy-task.sh
# Limits on a running service
systemctl show myservice.service -p MemoryMax -p CPUQuota
How the Three Work Together: Launching an Application
Watching one application start shows all three mechanisms in action:
- A process is created. The shell forks a child, which then execs the browser program.
- Memory is provided. The process gets a virtual address space. Its code and libraries are mapped in, and pages are loaded from disk only as they are actually used.
- The scheduler grants CPU time. The process becomes runnable and receives turns on the available cores, shared with everything else.
- Demand grows. Opening more tabs asks for more memory and more CPU. The kernel allocates pages, reclaims cache if needed, and may swap out idle pages.
- Resources are released. When the process exits, its memory and other resources are reclaimed, and the exit status is held until the parent collects it.
The resources are not independent. A process cannot run without memory, a memory shortage causes swapping that creates disk waiting, and disk waiting leaves the CPU idle even though work is queued. That interdependence is why troubleshooting means looking at all three together.
The Monitoring Toolkit
| Tool | What It Shows | Best Used For |
|---|---|---|
top |
Live processes, CPU, memory, and load. Press P to sort by CPU, M by memory, 1 for per-core view, k to kill, r to renice, q to quit. |
A first look at what is busy right now |
htop |
An interactive, easier-to-use version of top (usually needs installing) | Sorting, filtering, and navigating processes comfortably |
ps |
A snapshot of processes with the columns you choose | Scripting and precise queries |
free -h |
Memory and swap totals, including the available figure | Quick memory health check |
vmstat 1 5 |
Processes, memory, swap, I/O, and CPU over time | Telling CPU, memory, and I/O problems apart |
uptime |
How long the system has been up, and the load averages | A one-line summary of system load |
iostat, sar, pidstat |
Disk, historical, and per-process statistics (from the sysstat package) | Deeper investigation and history |
/proc/meminfo, /proc/loadavg |
The raw kernel counters the tools above read from | Understanding where the numbers come from |
Understanding Load Average
uptime
# 14:32:10 up 12 days, 3:41, 2 users, load average: 0.85, 1.20, 2.40
# | | |
# 1 min 5 min 15 min
# How many CPU cores does this system have?
nproc
Load average counts the processes that are running, waiting for a CPU, or (on Linux) stuck in uninterruptible sleep, averaged over 1, 5, and 15 minutes. Interpret it relative to the number of cores:
- On a 4-core system, a load of 4 means the cores are fully busy, and a sustained load well above 4 means work is queueing
- The three numbers show the trend. If the 1-minute figure is much higher than the 15-minute figure, load is rising. If it is lower, the busy period is ending.
- High load with low CPU use usually means processes are waiting on I/O. Because Linux counts uninterruptible sleep, a slow disk can drive load up while the CPU sits idle.
Reading vmstat
# Report every second, five times
vmstat 1 5
# procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
# r b swpd free buff cache si so bi bo in cs us sy id wa st
# 1 0 0 1254320 88120 4501232 0 0 12 30 210 480 5 2 92 1 0
| Column | Meaning | What a Problem Looks Like |
|---|---|---|
r |
Processes running or waiting for CPU | Consistently higher than the number of cores means CPU contention |
b |
Processes blocked in uninterruptible sleep | Non-zero for long periods points to slow I/O |
swpd |
Amount of swap in use | Not a problem by itself |
si and so |
Memory swapped in from, and out to, disk per second | Sustained non-zero values mean active swapping and memory pressure |
bi and bo |
Blocks read from and written to disks | Very high values with high wa suggest a disk bottleneck |
us and sy |
CPU time in user programs and in the kernel | High us is application work. High sy can mean heavy system calls or I/O handling. |
id |
Idle CPU time | Near zero means the CPU is saturated |
wa |
CPU time spent waiting for I/O | High values mean the CPU is idle because storage is slow |
st |
Time stolen by the hypervisor in a virtual machine | Non-zero in a VM means the host is overcommitted |
Diagnosing a Slow System: A Step-by-Step Approach
When someone says "the server is slow", resist the urge to guess. Work through the three resources in order, and let the numbers tell you which one is the problem.
# 1. How loaded is the system, and how many cores does it have?
uptime
nproc
# 2. Is it CPU, memory, or I/O? Watch for a few seconds
vmstat 1 5
# 3. If CPU is busy: which processes are using it?
ps -eo pid,user,%cpu,%mem,stat,cmd --sort=-%cpu | head -10
# 4. If memory is tight: how much is really available, and who is using it?
free -h
ps -eo pid,user,rss,vsz,cmd --sort=-rss | head -10
# 5. Is the system swapping heavily? (look at si and so in vmstat)
swapon --show
# 6. Has the kernel already killed something?
journalctl -k | grep -i -E "out of memory|oom"
# 7. If load is high but CPU is idle: is anything stuck waiting on disk?
ps -eo pid,stat,wchan:20,cmd | awk '$2 ~ /^D/'
A note on the memory columns in ps: RSS is the physical memory a process is actually using right now. VSZ is its total virtual size, which can be far larger and is rarely a useful measure of real consumption on its own. Sort by RSS when you are hunting for memory hogs.
Common Symptoms and What to Check
| Symptom | What to Check | Likely Cause |
|---|---|---|
| High load, high CPU use | top sorted by CPU, vmstat r and us |
A CPU-heavy process or too many runnable tasks |
| High load, low CPU use | vmstat wa and b, processes in D state |
Slow disk or network storage |
| Little free memory | free -h and the available column |
Often normal cache use. Only a problem if available is also low. |
| Everything slow, disk busy | vmstat si and so |
Swapping because of memory pressure |
| A service disappeared | journalctl -k for OOM messages, systemctl status |
Killed by the OOM killer or by a cgroup limit |
| A process will not die | State in ps: D or Z |
Uninterruptible I/O wait, or a zombie awaiting its parent |
| Many zombie processes | The parent PID of each zombie | A parent that is not collecting exit statuses |
| One process makes the system sluggish | Its CPU and I/O use, and its nice value | Needs renice or ionice, or a resource limit |
Managing Processes with Signals
The kill command does not necessarily kill. It sends a signal, and the process decides how to react to most of them. Choosing the right signal is the difference between a clean shutdown and lost data.
| Signal | Number | Effect | When to Use |
|---|---|---|---|
SIGTERM |
15 | Politely asks the process to terminate. It can clean up first. This is the default. | Always try this first |
SIGKILL |
9 | Forces immediate termination. The process cannot catch or ignore it, and cannot clean up. | Last resort when SIGTERM is ignored |
SIGHUP |
1 | Traditionally "hang up". Many daemons reload their configuration. | Reloading a service without restarting |
SIGSTOP / SIGCONT |
19 / 18 | Pause a process, then resume it | Temporarily freezing a heavy process |
SIGINT |
2 | Interrupt, the same as pressing Ctrl+C | Stopping a foreground command |
# Ask a process to terminate cleanly (SIGTERM is the default)
kill 1234
# Force it if it ignores the request
kill -9 1234
# Signal by name instead of PID
pkill nginx
pkill -f "python app.py"
# List all signals
kill -l
# Pause and resume a CPU-heavy process
kill -STOP 1234
kill -CONT 1234
Even kill -9 cannot remove a process in uninterruptible sleep (D state) until its I/O completes, and it has no effect on a zombie. Both cases need the underlying cause fixed rather than a stronger signal.
Common Mistakes
- Panicking over low "free" memory. Linux fills spare RAM with cache by design. Look at
available, and at swap activity, before deciding there is a problem. - Reaching for
kill -9first. It skips cleanup, so databases and services can leave corrupted or locked files. Use SIGTERM, wait, and escalate only if needed. - Reading load average without knowing the core count. A load of 8 is idle-ish on a 32-core server and a crisis on a 2-core one.
- Assuming high load means high CPU. On Linux it can equally mean processes blocked on disk. Check
vmstatwabefore blaming a program. - Treating any swap use as a failure. Some swap use is healthy. The warning sign is continuous swapping, shown by sustained
siandso. - Using
niceto fix a disk problem. Nice affects CPU scheduling only. For I/O-heavy processes useionice. - Setting a runaway process to a real-time policy. It can starve everything else, including your ability to log in and fix it.
- Judging memory use by
VSZ. Virtual size includes memory that is mapped but never touched. UseRSS. - Disabling swap on a busy system without checking. Running
swapoffforces everything in swap back into RAM, and if there is not enough room it can trigger the OOM killer.
Quick Reference
| Task | Command |
|---|---|
| List all processes | ps aux |
| Show the process tree | pstree -p |
| Top CPU consumers | ps -eo pid,user,%cpu,cmd --sort=-%cpu | head |
| Top memory consumers | ps -eo pid,user,rss,cmd --sort=-rss | head |
| Live monitoring | top or htop |
| Memory and swap overview | free -h |
| Active swap areas | swapon --show |
| CPU, memory, swap, and I/O over time | vmstat 1 5 |
| Load average and core count | uptime and nproc |
| Start a command at lower priority | nice -n 10 command |
| Change a running process's priority | renice -n 5 -p PID |
| Lower the I/O priority of a command | ionice -c 3 command |
| Terminate a process cleanly | kill PID |
| Force-terminate a process | kill -9 PID |
| Find recent OOM kills | journalctl -k | grep -i oom |
| Limit a command's resources | sudo systemd-run --scope -p MemoryMax=500M command |
Where This Fits in Linux Certifications
Identifying resource-hungry processes and controlling them is part of core Linux administration, and it appears in both the RHCSA and LFCS skill areas. Typical tasks ask you to find the process using the most CPU or memory, change a process's priority with nice or renice, terminate a process with the appropriate signal, and read memory and load information. As with any certification, check the current published objectives for your exam version.
Conclusion
Linux resource management is why one machine can run hundreds of programs at once and stay responsive. The kernel tracks every process, schedules CPU time among them, and gives each its own virtual memory, reclaiming and reshuffling it as demand changes.
- A process is a running program with a PID, a parent, and a state. Zombies are finished processes waiting for their parent, and cannot be killed.
- The scheduler shares CPU time. Nice values influence it for normal processes, and real-time policies should be used sparingly.
- Virtual memory isolates processes and lets the kernel use pages flexibly, including as a file cache
- Low
freememory is usually normal. Watchavailableand swap activity instead. - Load average must be read against the core count, and high load with idle CPU usually points to I/O
- When resources run out, swap and the OOM killer are the last lines of defense
- Troubleshoot in order:
uptime,vmstat, thenpsortopfor the guilty process, and read the numbers before acting
For anyone moving toward system administration, DevOps, cloud engineering, or security, this knowledge turns the command line from a set of memorized commands into a view of what the system is actually doing. Once you can read vmstat and free with confidence, you can find the cause of most slowdowns in minutes.