Linux Memory¶
36 cards — 🟢 9 easy | 🟡 9 medium | 🔴 11 hard
🟢 Easy (9)¶
1. What is the difference between MemFree and MemAvailable in /proc/meminfo?
Show answer
MemFree - The amount of unused physical RAM in your systemMemAvailable - The amount of available memory for new workloads (without pushing system to use swap) based on MemFree, Active(file), Inactive(file), and SReclaimable.
Remember: `free -h`: available = free + reclaimable cache. That's what matters.
Gotcha: High "used" is normal — Linux caches aggressively. Check "available."
2. What is the difference between paging and swapping?
Show answer
Both involve moving data between RAM and disk, but at different granularities.Paging:
- Moves individual pages (4KB typically)
- Fine-grained memory management
- Pages moved to swap as needed
- Demand paging: load pages only when accessed
- Modern systems primarily use paging
Swapping (traditional):
Remember: Swap = disk overflow. swappiness(0-100) controls aggressiveness. K8s disables.
Gotcha: Swap masks memory problems. Databases/K8s prefer `swapoff -a`.
3. What is a swap partition? What is it used for?
Show answer
Swap is disk space used as virtual memory extension.Purpose:
- Extends available memory beyond physical RAM
- Holds inactive memory pages
- Enables hibernation (swap must be >= RAM)
- Prevents OOM when RAM is full
Types:
- Swap partition: Dedicated disk partition
Remember: Swap = disk overflow. swappiness(0-100) controls aggressiveness. K8s disables.
Gotcha: Swap masks memory problems. Databases/K8s prefer `swapoff -a`.
4. What is the return value of malloc?
Show answer
malloc returns a pointer to allocated memory, or NULL on failure.Returns:
- Success: Pointer to allocated memory (void*)
- Failure: NULL pointer
Important notes:
- Memory is uninitialized (garbage values)
- Use calloc() for zero-initialized memory
- Always check for NULL before use
Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
5. What is tmpfs and when would you use a RAM-backed filesystem?
Show answer
tmpfs is a RAM-based temporary filesystem.Features:
- Stored in memory (and swap)
- Very fast I/O
- Contents lost on reboot
- Size is flexible (grows/shrinks)
Common uses:
- /tmp - Temporary files
- /run - Runtime data
- /dev/shm - Shared memory
Mount: mount -t tmpfs -o size=1G tmpfs /mnt/ramdisk
Benefits:
- Speed (no disk I/O)
- Automatic cleanup on reboot
- Reduces disk wear (SSDs)
Difference from ramfs: tmpfs can use swap, has size limits.
Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
6. Explain what is OOM killer
Show answer
OOM Killer terminates processes when system runs out of memory.When triggered:
- Physical memory exhausted
- Swap full or disabled
- Cannot allocate requested memory
How it selects:
- Calculates oom_score (0-1000) for each process
- Higher score = more likely to die
Remember: OOM = kernel kills processes when memory exhausted. `dmesg | grep oom` for victims.
7. How to check memory stats and CPU stats?
Show answer
You'd use `top/htop` for both. Using `free` and `vmstat` command we can display the physical and virtual memory statistics respectively. With the help of `sar` command we see the CPU utilization & other stats (but `sar` isn't even installed in most systems).Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
8. What does the man command provide?
Show answer
The manual page for a specific command.Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
Remember: `man` sections: 1=commands, 2=syscalls, 3=library, 5=file formats, 8=admin. `man 5 passwd` shows the file format, not the command.
Example: `man -k keyword` searches all man pages. `man 2 open` shows the open() system call documentation.
9. Explain the file content commands along with the description.
Show answer
- `head`: to check the starting of a file.- `tail`: to check the ending of the file. It is the reverse of head command.
- `cat`: used to view, create, concatenate the files.
- `more`: used to display the text in the terminal window in pager form.
- `less`: used to view the text in the backward direction and also provides single line movement.
Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
Remember: `head -n 20` = first 20 lines. `tail -f` = follow live. `less` = paginate (search with /). `cat` = dump all.
Gotcha: `cat` on a huge file floods the terminal. Use `less` or `head` for large files.
🟡 Medium (9)¶
1. How to check how much free memory a system has? How to check memory consumption by each process?
Show answer
You can use the commands `top` and `free`Remember: `free -h`: available = free + reclaimable cache. That's what matters.
Gotcha: High "used" is normal — Linux caches aggressively. Check "available."
2. What does the OOM killer consider when selecting a process?
Show answer
Memory usage, reclaimable memory, `oom_score_adj`, root status, and system impact.Inspect via `/proc/
Remember: OOM = kernel kills processes when memory exhausted. `dmesg | grep oom` for victims.
3. Why does free not show all available memory as free?
Show answer
Linux aggressively uses RAM for cache and buffers. Free memory is wasted memory.**Understanding the output**:
```\n total used free shared buff/cache available\nMem: 16G 4G 1G 200M 11G 10G\n```
Remember: `free -h`: available = free + reclaimable cache. That's what matters.
Gotcha: High "used" is normal — Linux caches aggressively. Check "available."
4. How to debug binaries?
Show answer
Several tools for debugging binaries:1. gdb - GNU Debugger (breakpoints, stepping, variables)
2. strace - System call tracer
3. ltrace - Library call tracer
4. objdump - Disassembler
5. nm - Symbol listing
6. ldd - Shared library dependencies
7. valgrind - Memory debugging (leaks, invalid access)
Compile with -g flag for debug symbols.
Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
5. What is the Linux kernel OOM killer and when does it activate?
Show answer
OOM (Out of Memory) Killer terminates processes when memory is exhausted.When triggered:
- Physical RAM exhausted
- Swap full or disabled
- Memory allocation fails
How it selects victims:
- oom_score for each process (0-1000)
- Higher score = more likely to die
Remember: OOM = kernel kills processes when memory exhausted. `dmesg | grep oom` for victims.
6. Explain RSS vs VSZ vs PSS.
Show answer
They describe different views of process memory usage and how shared pages are counted.- VSZ: total virtual address space, including mapped files, shared libs, and reserved but unused pages.
- RSS: physical pages currently resident for the process, but shared pages are fully counted for each process.
Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
7. How do you identify and resolve performance bottlenecks in a data center?
Show answer
Identifying and resolving performance bottlenecks in a data center involves a systematic approach: **Monitoring:* • Utilize monitoring tools to collect performance metrics, including CPU utilization, memory usage, disk I/O, and network traffic. **Analysis:* • Analyze collected data to identify patterns and anomalies. Look for spikes or consistent high utilization in specific resources. **Profiling:* • Use profiling tools to identify performance bottlenecks in software applications or specific server processes.Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
8. How would you diagnose a sudden increase in server resource utilization?
Show answer
• Identify the Resource: • Determine which resource is experiencing a sudden increase (CPU, memory, disk, or network). • Check Resource Monitoring: • Use monitoring tools (such as Task Manager or Performance Monitor) to review real-time resource utilization. • Review Recent Changes: • Investigate recent changes in software, configurations, or updates that may be contributing to increased utilization. • Check for Malware: • Scan for malware or unauthorized processes that could be consuming resources.Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
9. What happens when you execute ls -l?
Show answer
* Shell reads the input using getline() which reads the input file stream and stores into a buffer as a string* The buffer is broken down into tokens and stored in an array this way: {"ls", "-l", "NULL"}
* Shell checks if an expansion is required (in case of ls *.c)
* Once the program in memory, its execution starts. First by calling readdir()
Notes:
* getline() originates in GNU C library and used to read lines from input stream and stores those lines in the buffer
🔴 Hard (11)¶
1. What causes high kswapd CPU usage?
Show answer
kswapd is the kernel swap daemon that reclaims memory pages. High CPU means memory pressure:**Causes**:
* Memory pressure - system needs to reclaim pages constantly
* Excessive page reclamation - too much dirty memory
* Memory leaks - constant allocation without release
* Overcommit with active workloads
* Poor swappiness tuning for workload type
Remember: Swap = disk overflow. swappiness(0-100) controls aggressiveness. K8s disables.
Gotcha: Swap masks memory problems. Databases/K8s prefer `swapoff -a`.
2. How mount a temporary ram partition?
Show answer
```bash\n# -t - filesystem type\n# -o - mount options\nmount -t tmpfs tmpfs /mnt -o size=64M\n```Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
3. What is vm.swappiness and how does it control memory management?
Show answer
Controls the kernel's tendency to swap anonymous memory vs reclaim page cache.**Range**: 0-200 (0-100 traditionally, 200 with newer kernels)
**What it does**:
* Higher value: More willing to swap out inactive anonymous pages
* Lower value: Prefers keeping anonymous memory in RAM, reclaims file cache instead
**It's NOT a threshold** - common misconception.
Remember: Swap = disk overflow. swappiness(0-100) controls aggressiveness. K8s disables.
Gotcha: Swap masks memory problems. Databases/K8s prefer `swapoff -a`.
4. How do you find and mitigate subtle memory leaks in a long-running process without restarting it?
Show answer
Use a combination of monitoring, analysis tools, and containment strategies.Detection and analysis:
- `smem` - shows PSS (Proportional Set Size) per process
- `pmap -x
- `valgrind --tool=massif` - heap profiler (if you can attach)
- Monitor `/proc/
- `/proc/
Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
5. Explain a real scenario where lowering swappiness makes performance worse.
Show answer
Low swappiness causes page cache starvation and increased I/O amplification.Scenario: Application server with hot working set of files
- swappiness=1 means "never swap, always drop page cache"
- Hot files constantly re-read from disk instead of staying cached
- Anonymous memory (rarely used) stays in RAM
- Result: massive I/O amplification, slower performance
Remember: Swap = disk overflow. swappiness(0-100) controls aggressiveness. K8s disables.
Gotcha: Swap masks memory problems. Databases/K8s prefer `swapoff -a`.
6. Explain how the Linux OOM killer selects which process to kill.
Show answer
The OOM killer uses /proc/Score calculation factors:
- Memory usage (primary factor) - RSS and swap consumption
- Process priority and niceness
- Heuristics: root processes get lower scores, child processes factor in
- Process age (newer processes may score higher)
Remember: OOM = kernel kills processes when memory exhausted. `dmesg | grep oom` for victims.
7. How does the Linux OOM killer decide what to kill?
Show answer
When memory is exhausted and can't be reclaimed, the OOM killer selects a victim:**oom_score calculation**:
* Based on memory usage (RSS)
* Adjusted by `oom_score_adj` (-1000 to 1000)
* -1000 = never kill, 1000 = always prefer
* Root processes get slight protection by default
**Selection criteria**:
* Highest score wins (gets killed)
Remember: OOM = kernel kills processes when memory exhausted. `dmesg | grep oom` for victims.
8. Why does Linux sometimes prefer killing a large cache-heavy process over a memory hog?
Show answer
The OOM killer targets unreclaimable memory, not total memory usage.Key points:
- Page cache is reclaimable - kernel can drop it under pressure
- Anonymous memory (heap, stack) requires swap or process death
- OOM scoring penalizes unreclaimable RSS, not total VSZ
- A process with 10GB page cache but 100MB anon memory is "safer" than one with 2GB anon
- "Big process != bad process" from O
Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
9. How would you check total available memory and CPU count on a Linux system without installing any tools?
Show answer
cat /proc/meminfo for memory (look at MemTotal, MemFree, MemAvailable) and cat /proc/cpuinfo or grep -c processor /proc/cpuinfo for CPU count. These files are always available.Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.
10. Rsync triggered Linux OOM killer on a single 50 GB file. How does the OOM killer decide which process to kill first? How to control this?
Show answer
The OOM killer selects processes to kill based on their `oom_score` (viewable at `/proc/To control it:
- Check a process score: `cat /proc/
- Protect a process: `echo -17 > /proc/
- Use cgroups to set `oom.priority` — 0 makes processes immune, higher values make them preferred targets
- System-wide: `/proc/sys/vm/overcommit_memory` controls whether the kernel overcommits memory (default 0 = heuristic overcommit)
11. An application encounters some performance issues. You should to find the code we have to optimize. How to profile app in Linux environment?
Show answer
Key profiling tools on Linux:1. **top** (batch mode): `top -b -p $(pidof app)` — shows CPU, memory, threads over time
2. **ps**: `ps --format pid,pcpu,cputime,etime,size,vsz,cmd -p $(pidof app)`
3. **perf**: Record with `perf record -g -p $(pidof app) sleep 10`, analyze with `perf report --stdio` — shows per-function CPU breakdown and call chains
4. **valgrind/callgrind**: `valgrind --tool=callgrind ./binary` then visualize with `kcachegrind`
5. **pstack/lsstack**: Quick stack snapshots of a running process
Remember: Linux memory: RAM→Cache→Swap. `free -h` overview. "available" is key metric.
Gotcha: "unused RAM is wasted RAM" — Linux caches aggressively. This is healthy behavior.