Process_management
Chapter 16: Process Management
Section titled “Chapter 16: Process Management”Understanding and Controlling Linux Processes
Section titled “Understanding and Controlling Linux Processes”16.1 Process Fundamentals
Section titled “16.1 Process Fundamentals”What is a Process?
Section titled “What is a Process?”A process is an instance of a running program. Each process has its own memory space, system resources, and execution context. In Linux, everything is treated as a file, and processes are no exception - they’re managed through the /proc filesystem.
Linux Process Architecture+------------------------------------------------------------------+| || Process Structure || +-------------------------------------------------------------+|| | Process Control Block (PCB) ||| | +---------------------------------------------------+ ||| | | Process ID (PID) | ||| | | Parent PID (PPID) | ||| | | User ID (UID) / Group ID (GID) | ||| | | Process State | ||| | | Program Counter (PC) | ||| | | CPU Registers | ||| | | Memory Management Info | ||| | | I/O Status Information | ||| | | Accounting Information | ||| | +---------------------------------------------------+ ||| +-------------------------------------------------------------+|| | || v || +-------------------------------------------------------------+|| | Virtual Memory ||| | +---------------------------------------------------+ ||| | | Text Segment (Code) | ||| | | Data Segment (Initialized data) | ||| | | BSS Segment (Uninitialized data) | ||| | | Heap (Dynamic memory) | ||| | | Stack (Function calls, local variables) | ||| | +---------------------------------------------------+ ||| +-------------------------------------------------------------+|| || Kernel Space || +-------------------------------------------------------------+|| | Process Table | File Descriptors | Network Sockets ||| +-------------------------------------------------------------+|| |+------------------------------------------------------------------+Process States
Section titled “Process States” Process State Diagram+------------------------------------------------------------------+| || States in /proc/[pid]/stat: || || +---------+ || | R | Running/Runnable - Executing or ready to execute|| +----+----+ || | || | (Scheduler) || v || +---------+ (I/O Wait) +---------+ || | S |<---------------------->| D | || | Sleeping| | Disk Sleep| || +---------+ +---------+ || | || | (Stop signal) || v || +---------+ || | T | Stopped - Suspended (Ctrl+Z, SIGSTOP) || +---------+ || | || | (Exit) || v || +---------+ || | Z | Zombie - Terminated but not reaped by parent || +---------+ || || Additional States: || +----------------------------------------------------------+ || | I | Idle kernel thread | || | K | Killable (sleeping, can be killed) | || | P | Parked (parked process) | || | X | Dead (should never be seen) | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+16.2 Viewing Processes
Section titled “16.2 Viewing Processes”ps Command
Section titled “ps Command”# Basic process listingps # Current shell processesps -e # All processesps -ef # Full formatps -eF # Extra fullps -eo pid,ppid,user,comm,%cpu,%mem,etime
# Common optionsps aux # BSD style (a=all, u=user, x=extended)ps -ef # Standard styleps -eLf # Threads (LWP, NLWP)ps -C nginx # By command nameps -p 1234 # By PIDps -U username # By user
# Sortingps -eo pid,ppid,%cpu,%mem,comm --sort=-%cpu # By CPUps -eo pid,ppid,%cpu,%mem,comm --sort=-%mem # By memory
# Tree viewps -ef --forestps -ejHpstree
# Custom outputps -eo pid,ppid,state,cmdps -eo pid,ppid,state,etime,cmd
# Header (show column names)ps -eo pid,ppid,user,comm,%cpu,%mem,etime --headerstop and htop
Section titled “top and htop”# top - Interactive process viewertop # Defaulttop -u username # User's processes onlytop -p 1234 # Specific PIDtop -d 1 # Refresh every 1 secondtop -n 5 # Run 5 iterationstop -H # Show threadstop -c # Show command linetop -1 # Show per-CPU
# Interactive commands in top:# P - sort by CPU# M - sort by memory# T - sort by time# k - kill process# r - renice process# f - field manager# W - write config
# htop - Enhanced tophtop # Interactivehtop -u username # Filter by userhtop -p 1234,5678 # PIDshtop -d 10 # Delay
# htop interactive:# F1 - Help# F2 - Setup columns# F3 - Search# F4 - Filter# F5 - Tree view# F6 - Sort by# F7 - Nice -# F8 - Nice +# F9 - Kill# F10 - QuitProcess Information in /proc
Section titled “Process Information in /proc”# Process informationls -la /proc/1234/ # Process infocat /proc/1234/status # Detailed statuscat /proc/1234/cmdline # Command line (null-separated)cat /proc/1234/environ # Environment (null-separated)cat /proc/1234/fd/ # File descriptorscat /proc/1234/maps # Memory mapscat /proc/1234/statm # Memory statisticscat /proc/1234/io # I/O statistics
# Process status infocat /proc/1234/status | grep -E "Name|Pid|State|Threads|VmSize|VmRSS"
# Maps (loaded libraries)cat /proc/1234/maps
# File descriptorsls -la /proc/1234/fd/lsof -p 123416.3 Process Control
Section titled “16.3 Process Control”Sending Signals
Section titled “Sending Signals”# Signal types# SIGTERM (15) - Graceful termination (default)# SIGKILL (9) - Immediate termination# SIGINT (2) - Interrupt (Ctrl+C)# SIGSTOP (19) - Stop process# SIGCONT (18) - Continue stopped process# SIGHUP (1) - Hangup (reload config)# SIGUSR1 (10) - User-defined# SIGUSR2 (12) - User-defined
# Kill processkill 1234 # Send SIGTERMkill -9 1234 # Send SIGKILLkill -KILL 1234 # By name
# By patternpkill nginx # By namepkill -9 nginx # Force killpkill -u username # User's processespkill -f "pattern" # By command line
# Kill all processeskillall nginx # All nginxkillall -9 nginx # Forcekillall -u username # User's all
# Send specific signalkill -HUP 1234 # Reload configkill -USR1 1234 # User-defined
# Process groupskill -TERM -1234 # Kill process groupProcess Priority
Section titled “Process Priority”# Nice value (-20 to 19, lower = higher priority)# Root can go negative, regular users 0-19
# Start with prioritynice -n 10 command # Lower priority (10)nice -n -10 command # Higher priority (root only)nice --10 command # Alternative syntax
# Change priority of running processrenice 10 1234 # Set priorityrenice +5 -p 1234 # Increase (lower priority)renice -5 -p 1234 # Decrease (higher priority, root)renice 0 -u username # All user's processes
# View priorityps -eo pid,ppid,ni,cmd
# Toolstop # Press r to renicehtop # F7/F8 to niceBackground and Foreground
Section titled “Background and Foreground”# Run in backgroundcommand & # Run in backgroundnohup command & # Immune to hangupnohup command > output.txt 2>&1 &
# Jobs controljobs # List jobsjobs -l # With PIDs
# Foreground/Backgroundfg # Bring to foregroundfg %1 # Job 1 to foregroundfg %2 # Job 2 to foreground
# Backgroundbg # Resume stopped job in backgroundbg %1 # Resume job 1
# Disown from shelldisown %1 # Remove job from shelldisown -h %1 # Don't send SIGHUPdisown -a # All jobs
# Screen/tmuxscreen # New screen sessionscreen -S name # Named sessionscreen -r # Reattachscreen -ls # List sessions
tmux new -s name # New tmuxtmux attach -t name # Attachtmux ls # List16.4 Process Monitoring
Section titled “16.4 Process Monitoring”Monitoring Tools
Section titled “Monitoring Tools”# top/htop (interactive)tophtopbtop # Modern, GPU-accelerated
# Process specific infops aux | grep nginxpidof nginx # Get PIDpidof -s nginx # Single PIDpidof -x nginx # Include script names
# lsof - open fileslsof # All open fileslsof -p 1234 # Process fileslsof -u username # User's fileslsof -i # Network fileslsof -i :80 # Port 80lsof -i TCP:80 # TCP port 80lsof +D /var/log # Files in directory
# ltrace/strace - system callsstrace -p 1234 # Trace processstrace -f -e openat # Specific callsstrace -c # Count syscallsstrace -o file.log # To file
# Time and resource usagetime commandtime -v command # Verbose/usr/bin/time -v command
# Continuous monitoringwatch -n 1 'ps aux | grep nginx'Resource Usage
Section titled “Resource Usage”# CPU usage per processps -eo pid,comm,%cpu --sort=-%cpu | head -10top # Press 1 for per-CPU
# Memory usageps -eo pid,comm,%mem --sort=-%mem | head -10pmap -x 1234 # Memory mapcat /proc/1234/status | grep Vm
# I/O statisticsiotop # I/O usageiotop -o # Only activeiostat -x 1 # Disk I/Opidstat -d 1 # Per-process I/O
# Network statisticsss -tp # TCP socketsss -up # UDP socketsnetstat -tp # Connectionsnethogs # Per-process network
# Thread countps -o nlwp= -p 1234top -H -p 123416.5 Process Accounting
Section titled “16.5 Process Accounting”Process Accounting Setup
Section titled “Process Accounting Setup”# Enable accountingsudo apt install acct # Debian/Ubuntusudo yum install psacct # RHEL/CentOS
# Start servicesudo systemctl enable psacctsudo systemctl start psacct
# Commandslastcomm # Previous commandslastcomm --user username # User's commandslastcomm --tty tty1 # Terminalsa # Summarysa -m # Per-usersa -u # Per-command
# Process accounting filels -la /var/log/account/cat /var/log/account/pacct*Audit Logging
Section titled “Audit Logging”# Using auditdsudo apt install auditdsudo auditctl -w /usr/bin/nginx -p x -k nginx_execsudo ausearch -k nginx_exec
# Monitor process creationsudo auditctl -a task,alwayssudo ausearch -sc execve16.6 Zombie and Orphan Processes
Section titled “16.6 Zombie and Orphan Processes”Understanding Zombie Processes
Section titled “Understanding Zombie Processes” Zombie Process Lifecycle+------------------------------------------------------------------+| || Normal Process: || || 1. Parent forks child || 2. Child runs and exits || 3. Parent reads exit status (wait()) || 4. Kernel removes process || || Zombie Process: || || 1. Parent forks child || 2. Child runs and exits || 3. Parent doesn't call wait() || 4. Child becomes ZOMBIE (dead but not cleaned) || 5. Parent calls wait() → process removed || || Orphan Process: || || 1. Parent forks child || 2. Parent exits before child || 3. Child adopted by init (PID 1) || 4. init calls wait() when child exits || |+------------------------------------------------------------------+Finding and Handling
Section titled “Finding and Handling”# Find zombie processesps aux | grep Zps -eo pid,ppid,state,cmd | grep Ztop # Z in status column
# Parent of zombieps -eo pid,ppid,state,cmd | grep Z
# Kill zombie# Usually can't kill zombie - it's already dead# Must kill parent processkill -9 <parent_pid>kill -SIGCHLD <parent_pid>
# If parent won't die# Only option: restart parent or reboot
# Prevent zombies:# - Properly call wait() in code# - Use signal handlers for SIGCHLD# - For orphaned: init handles automatically16.7 Advanced Process Management
Section titled “16.7 Advanced Process Management”cgroups and Namespaces
Section titled “cgroups and Namespaces”# Using cgroups v2# Create cgroupsudo mkdir -p /sys/fs/cgroup/mygroup/echo 500000000 > /sys/fs/cgroup/mygroup/memory.maxecho 100000 > /sys/fs/cgroup/mygroup/cpu.max
# Add process to cgroupecho <pid> > /sys/fs/cgroup/mygroup/cgroup.procs
# Using systemd (easier)systemd-run --scope -p MemoryMax=512M /bin/bash
# Resource control in systemd# See Chapter 17 systemd
# Namespaces (unshare)# Create new network namespacesudo unshare -n bash# Create new PID namespacesudo unshare -p bash# Create new mount namespacesudo unshare -m bashPerformance Tuning
Section titled “Performance Tuning”# Kernel tuning for process handling# Process limits# /etc/security/limits.conf* soft nofile 65535* hard nofile 65535* soft nproc 65535* hard nproc 65535
# Process scheduling# nice values affected by:# /etc/nicevalues.conf
# CPU affinitytaskset -p 0x1 1234 # CPU 0 onlytaskset -cp 0,1 1234 # CPUs 0 and 1taskset -a -p 0x3 1234 # All CPUs 0-116.8 Container Process Management
Section titled “16.8 Container Process Management”Containers and Processes
Section titled “Containers and Processes”# Docker process listingdocker ps # Running containersdocker ps -a # All containersdocker top container # Processes in container
# crictl (Kubernetes)crictl ps # Container processes
# Namespaces inside container# Each container has own:# - PID namespace (process IDs)# - Network namespace (network stack)# - Mount namespace (filesystems)# - UTS namespace (hostname)# - IPC namespace (shared memory)# - User namespace (UIDs/GIDs)
# Process limits in containersdocker run --cpus=2 containerdocker run --memory=512m containerdocker run --pids-limit=100 container16.9 Interview Questions
Section titled “16.9 Interview Questions”Basic Questions
Section titled “Basic Questions”-
What is a process in Linux?
- An instance of a running program with its own memory space, PID, and resources
-
What are the different process states?
- R (Running), S (Sleeping), D (Disk Sleep), T (Stopped), Z (Zombie)
-
How do you list all processes?
- ps -ef, ps aux, top, htop
-
What is the difference between kill and pkill?
- kill takes PID, pkill can match by name, user, etc.
-
What is a zombie process?
- A terminated process whose parent hasn’t read its exit status
Intermediate Questions
Section titled “Intermediate Questions”-
What is the difference between nice and renice?
- nice sets priority at start, renice changes running process
-
How do you run a process in the background?
- Using &, nohup, screen, tmux, disown
-
What is the init process?
- PID 1, ancestor of all processes, handles orphaned processes
-
How do you find processes by name?
- pgrep, pkill, ps aux | grep
-
What is the difference between SIGTERM and SIGKILL?
- SIGTERM allows graceful shutdown, SIGKILL is immediate
Advanced Questions
Section titled “Advanced Questions”-
How does the Linux scheduler work?
- Uses CFS (Completely Fair Scheduler), weights by nice value and runtime
-
What are cgroups and how are they used?
- Control groups for resource limiting (CPU, memory, I/O)
-
What are namespaces?
- Kernel feature for isolation (PID, network, mount, etc.)
-
How do you prevent zombie processes?
- Parent must call wait() or use SIGCHLD handler
-
What is the difference between OOM killer and process priority?
- OOM killer kills processes when memory exhausted, priority affects CPU scheduling
Summary
Section titled “Summary”Process management is fundamental to Linux administration:
Quick Reference+------------------------------------------------------------------+| || Process Viewing: || +----------------------------------------------------------+ || | ps aux | All processes | || | top/htop | Interactive viewer | || | pgrep pattern | Find by pattern | || | lsof -p PID | Open files | || +----------------------------------------------------------+ || || Process Control: || +----------------------------------------------------------+ || | kill PID | Terminate gracefully | || | kill -9 PID | Force kill | || | pkill name | Kill by name | || | renice N PID | Change priority | || | nice -n N command | Start with priority | || +----------------------------------------------------------+ || || Background/Foreground: || +----------------------------------------------------------+ || | command & | Run in background | || | Ctrl+Z, bg | Background stopped | || | fg | Bring to foreground | || | nohup command & | Immune to hangup | || | screen/tmux | Terminal multiplexer | || +----------------------------------------------------------+ || || Key Terms: || +----------------------------------------------------------+ || | PID | Process ID | || | PPID | Parent PID | || | UID/GID | User/Group ID | || | Nice | Scheduling priority (-20 to 19) | || | Zombie | Dead but not cleaned | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+