Processes, resource usage, signals and the environment a program sees
Inspect process lifecycles, diagnose memory and CPU bottlenecks with top and free, handle POSIX termination signals, and master environment variable inheritance.
Contentsand lesson path
On this page
- Why it matters
- The Process Tree: PIDs, Forks, and the /proc Filesystem
- Diagnostic Toolchain: ps, top, free, df, and du
- Process Intercommunication: POSIX Signals
- Environment Variables: Scope and Subshell Inheritance
- Check your understanding
- Apply it
- Review prompt
Lessons of Linux CLI
- Finding your way around the filesystem: globs, nano, vim and sudoedit Concept · 20 min
- Who may read this file? Users, groups and mode bits Worked example · 20 min
- Answering questions from an access log with pipelines Lab · 25 min
- Processes, resource usage, signals and the environment a program sees Concept · 20 min
- Remote work over SSH: keys, tar archives, scp and rsync Lab · 25 min
- Check: diagnose a misbehaving host from the shell Knowledge check · 8 questions
What you will learn
- Inspect and control processes and environment variables, and work on remote hosts over SSH with key-based authentication.
01. Why it matters
When a server is slow or a service will not stop, the first questions are about processes. Which program is using the CPU? Is memory really running out, or does a number only look large? Did the service get the shutdown request, and did it have time to finish its work? Why does a script work in your terminal but not when a scheduler starts it?
This lesson covers four of them: how processes are created and where the kernel shows their state, how to read memory, CPU and disk numbers without being misled, how signals ask a program to stop or reload, and which environment variables a program receives from the process that started it.
02. The Process Tree: PIDs, Forks, and the /proc Filesystem
In Linux, every program in execution is represented as a process assigned a unique integer Process ID (PID). The operating system kernel spawns the initial user-space process—systemd or an init daemon—with PID 1 during boot. Every subsequent process on the host is created when an existing process calls the fork() (duplicating itself) and execve() (replacing its image with a new binary) system calls, establishing an explicit parent-child hierarchy.
Each process maintains:
- PID and PPID: A unique process identifier and its Parent Process ID.
- Real and Effective User/Group IDs: Determining file and resource access rights.
- File Descriptor Table: Pointers to open sockets, pipes, and files.
- Memory Address Space: Isolated virtual memory segments containing executable code, heap allocations, and stack frames.
The Linux kernel exposes the internal state of every active process via the virtual /proc directory. For example, for process PID 4520, you can inspect /proc/4520/cmdline to see the exact execution arguments, /proc/4520/environ for its environment variables, /proc/4520/fd/ for open file descriptors, and /proc/4520/status for detailed memory consumption and signal masks without invoking third-party utilities.
03. Diagnostic Toolchain: ps, top, free, df, and du
When alerts fire about latency or resource exhaustion, a few command-line tools answer most first questions:
ps(Process Snapshot):ps aux: Displays BSD-style snapshot of all running processes across all users.ps -eo pid,ppid,user,%cpu,%mem,cmd --sort=-%cpu | head -n 10: Sorts and prints the top 10 CPU-consuming processes on the host.VSZandRSScolumns (ps aux,ps -o pid,vsz,rss,cmd): both are in KiB.VSZ(virtual size) counts all the address space the process has mapped, including memory it reserved but never touched and files it mapped.RSS(resident set size) counts the pages that are in RAM right now. Linux gives a process physical pages only when it first touches them, soVSZis often far larger than RAM and says little about memory pressure; watchRSSand theavailablecolumn offreeinstead.
topandhtop(Real-time Process Monitoring):- Load Averages: Displays three floating-point values representing system load over 1, 5, and 15 minutes. On an 8-core CPU, a load average above 8.0 indicates that processes are actively queueing for CPU time or blocked on disk I/O.
- CPU Breakdown:
us(unprivileged user code),sy(kernel system calls),id(idle), andwa(iowait—high values indicate storage bottlenecks where CPUs sit idle waiting for disk reads/writes).
free -m(Memory Diagnostics):- Distinguishes between
free(completely unallocated RAM) andavailable(estimated RAM available for starting new applications without swapping, including easily reclaimable page cache and buffer memory).
- Distinguishes between
df -handdu -sh(Storage Capacity):df -h: Shows mounted filesystems, total capacities, and available disk space.df -i: Inspects filesystem inode usage. If a filesystem runs out of inodes (e.g. millions of tiny session files in/tmp), it will reject new file creation withNo space left on deviceeven if gigabytes of raw disk space remain free.du -sh /var/log/*: Calculates cumulative disk usage of files and directories within a target folder.
You can watch the difference with a short Python script. It reserves 4 GiB of address space with an anonymous mmap, which costs no RAM yet, then writes one byte into every 4 KiB page of the first 512 MiB, which makes the kernel hand over real pages. It reads the two numbers from /proc/self/status (lines VmSize and VmRSS), the same values ps shows as VSZ and RSS, so it needs only Python 3 on Linux, not ps. Save it as vsz_rss.py and run python3 vsz_rss.py on a machine with at least 1 GiB of free memory.
import mmap
def show(label):
# VmSize and VmRSS are the numbers ps prints as VSZ and RSS, in KiB
with open('/proc/self/status') as status:
fields = dict(line.split(':', 1) for line in status)
vsz = int(fields['VmSize'].split()[0]) // 1024
rss = int(fields['VmRSS'].split()[0]) // 1024
print(f'{label}: VSZ {vsz} MiB, RSS {rss} MiB')
buf = mmap.mmap(-1, 4 * 1024**3) # reserve 4 GiB of address space
show('after reserving 4 GiB')
for offset in range(0, 512 * 1024**2, 4096):
buf[offset] = 1 # touch 512 MiB, one byte per 4 KiB page
show('after touching 512 MiB')after reserving 4 GiB: VSZ 4117 MiB, RSS 8 MiB
after touching 512 MiB: VSZ 4117 MiB, RSS 520 MiBVSZ jumps by 4 GiB at once and then stays put, while RSS grows only by the 512 MiB that was touched. A service that reserves a large heap or maps big files looks the same in ps: a huge VSZ with a modest RSS is normal.
04. Process Intercommunication: POSIX Signals
Signals are asynchronous notifications sent by the Linux kernel or other processes to inform a program that a specific event has occurred. The kill command is the standard interface for sending signals to a target PID (e.g. kill -<SIGNAL> <PID>).
The signals you will meet most often are:
SIGTERM(Signal 15): The default termination request. It politely instructs the process to shut down. Well-architected services catchSIGTERM, stop accepting new incoming requests, finish processing in-flight tasks, flush database buffers, release locks, and exit cleanly.SIGINT(Signal 2): Terminal interrupt signal generated when a user pressesCtrl+Cin an interactive shell.SIGHUP(Signal 1): Hangup signal. Historically sent when a controlling terminal disconnected. Many daemons (such as Nginx, Prometheus, and PostgreSQL) catchSIGHUPby convention and reload their configuration files without restarting the process or dropping active connections. Some settings still need a full restart (PostgreSQL marks them in its documentation), so check the daemon's manual.SIGKILL(Signal 9): Termination carried out by the kernel. The process gets no chance to run any of its own code again.SIGKILLcannot be caught, blocked, or ignored by application code. One limit: a process stuck in uninterruptible sleep (stateDinps, usually waiting on a disk or network filesystem) dies only when that kernel operation returns. Use it as a last resort, when a process has not responded toSIGTERMwithin a reasonable grace period.SIGSTOP(Signal 19) andSIGCONT(Signal 18, both numbers as on x86 and Arm Linux): Pauses and resumes process execution (Ctrl+ZsendsSIGTSTP, a catchable variant ofSIGSTOP).kill -lprints the numbers on your system.
05. Environment Variables: Scope and Subshell Inheritance
Processes read their operational settings, secret keys, and runtime paths from an internal array of null-terminated key-value strings called the environment.
In a shell, there is a fundamental difference between a local shell variable and an exported environment variable. In the snippet below, a plain variable stays in the shell that set it, while an exported one is copied into the environment of every child process.
# Local shell variable (visible ONLY within current bash process)
DATABASE_URL=postgres://localhost:5432/db
# Exported environment variable (inherited by child processes)
export DATABASE_URL=postgres://localhost:5432/db
# Inline variable assignment for a single command invocation
PORT=3000 NODE_ENV=production node server.jsWhen a shell forks a child process to run a script or binary, the child receives an exact duplicate of the parent's exported environment variables. If a variable was created without export, it is not in the child's environment at all: the child sees it as unset, not as an empty string (X=1; bash -c 'echo "${X-unset}"' prints unset).
Furthermore, environment inheritance is strictly one-way (downward): a child process can modify its own local copy of an environment variable, but it has no ability to alter or inject variables into its parent shell process. Sourcing a script with source ./config.env or . ./config.env executes commands directly within the current shell context, bypassing subshell creation and enabling configuration export.
06. Check your understanding
07. Apply it
Incorporate these process management patterns into production service administration:
- Graceful Shutdown in Systemd: After
systemctl stop, systemd sends SIGTERM and waitsTimeoutStopSec=before it sends SIGKILL. The default is 90 seconds (DefaultTimeoutStopSec=insystemd-system.conf). Measure how long your daemon really needs to drain its queue, then set the value in the unit: raise it (for exampleTimeoutStopSec=300) for a worker that finishes long jobs, or lower it for a service that stops in a second, so a hung stop does not hold up a deploy or a reboot for 90 seconds. - SIGHUP Configuration Reloads: When rotating TLS certificates or modifying reverse proxy upstreams, run
systemctl reload nginxorsudo nginx -s reload(both signal only the nginx master process;kill -HUP $(pidof nginx)would also hit every worker) to reload configuration without dropping active TCP connections. - Inspect Inode Depletion: When disk capacity alerts trigger but
df -hshows plenty of space, always rundf -ito verify whether inode exhaustion is preventing new file creation.
08. Review prompt
Explain the architectural significance of PID 1 on Linux systems. Contrast free and available memory metrics when evaluating server health. Detail the operational differences between SIGTERM, SIGHUP, and SIGKILL, and explain why child processes cannot modify their parent shell's environment variables.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.