Module 1 · Lesson 97 of 103

Kernel answers and scripting prep

Explain processes, signals and pipelines through kernel mechanisms and plan five scripting answers with declared formats and failure handling.

  • Beginner to advanced
  • 8 min read
  • 16 min lab
What you will need

Ubuntu 24.04 with Bash and systemd in a VM, WSL2 with systemd enabled, or a lab host; OpsKit and Log Sentinel evidence; a peer or recorder; optional ARM board

Your place in the module
By the end you can 2 objectives
  • Apply shell parsing, validation and failure handling to five timed scripting scenarios.
  • Explain process states, signals and pipeline descriptors, blocking and failure handling through kernel mechanisms
Video coming soonKernel answers and scripting prep
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Provable answers and junior questions
  • Start with a direct answer, explain the mechanism, and support it with evidence and a limit.
  • Permissions, directory traversal and service identity must be checked together.
  • A hard link names the same file independently, while a symbolic link stores a path resolved from the link directory and may dangle
01

Explain processes, signals and pipelines through the kernel

4 min read

After answering junior questions on access and links, move to the kernel mechanisms behind processes, signals and pipelines. This lesson answers how to explain those mechanisms and plan the five scripting answers before typing.

It can contain several threads, which are execution paths sharing much of that state. The kernel schedules runnable threads onto processors.

Question: What do ps fields tell you? On Ubuntu with procps, choose explicit fields rather than remembering one display layout. This command sorts processes by reported CPU usage:

bash
ps -eo pid,ppid,user,stat,pcpu,pmem,rss,args --sort=-pcpu

PID identifies the process; PPID identifies its parent. USER is the displayed effective user. STAT begins with a state letter and may include flags. R means running or runnable, S interruptible sleep, D uninterruptible sleep, and Z a terminated child awaiting collection.

RSS is resident memory, reported here in KiB. It can include pages shared with other processes, so summing RSS can overcount physical use. %MEM expresses RSS as a percentage of physical memory. %CPU in ps reflects CPU time over the process lifetime, rather than a fresh sampling interval. A BusyBox ps may support fewer fields and options.

Question: Why use kill before kill -9? Each has a default action, but many signals can be handled or ignored. kill PID normally sends SIGTERM. It gives a cooperating program a chance to finish and clean up.

SIGKILL, selected by kill -9 PID, cannot be caught, blocked or ignored. User-space cleanup handlers cannot run. It still may not immediately remove a task stuck in an uninterruptible kernel wait. A zombie has already exited; its parent must collect its status.

For a managed service, prefer its documented systemctl stop workflow. It tracks the service's processes and stops them according to configured rules. For a standalone process, confirm its identity before sending a signal. Numeric process identifiers can be reused; a later kill could target a different process.

Question: How do grep, sed and awk differ? grep selects matching lines. sed applies text-editing commands to a stream. awk splits records into fields and supports calculations and grouped summaries. A stream is data read in sequence, without requiring the whole input in memory.

For a known log format, use grep for a quick selection and awk for counts. Avoid parsing structured formats such as JSON with field positions designed for plain text. Choose a parser that understands their structure.

1Describe a pipeline's connections

Descriptor 0 conventionally means standard input, 1 standard output and 2 standard error. A shell pipe normally connects one command's descriptor 1 to the next command's descriptor 0.

The shell creates pipes and starts commands, often using child processes. A child may replace its program using execve, the kernel interface for program execution. This replacement preserves process identity. Shell optimisations mean you should not promise one new process for every command.

2Explain blocking and failure

A pipe has finite kernel buffering. A writer can wait when it fills. A reader sees end-of-file only when all write-end references close. If no reader remains, a write can generate SIGPIPE. Keeping an unused descriptor open can therefore make a pipeline hang.

In Bash, pipeline status normally comes from the last command. set -o pipefail instead exposes the rightmost nonzero status. An early-exiting consumer can give an upstream producer SIGPIPE, so distinguish expected early termination from lost data. Strict mode commonly means set -euo pipefail: exit-on-error rules, unset-variable checks and pipeline failure handling. -e has exceptions, including commands tested by if; handle expected failures explicitly.

Going deeperFollow the descriptor, not just the filename

Linux exposes process descriptors under /proc/PID/fd. A renamed or unlinked log can remain open there. The descriptor refers through an open-file description, a kernel object carrying state such as an offset, to the file. This explains both pipeline lifetime problems and storage retained by deleted logs. In kernel sources, fs/pipe.c implements pipes and kernel/signal.c contains signal machinery; follow the source matching your target kernel.

A pipe connects descriptorsShellProducerKernel pipeConsumerCreate pipeConnectoutput; startConnect input; startWrite bytesRead bytesEOF afterwriters close1. Shell → Kernel pipeCreate pipe2. Shell → ProducerConnect output; start3. Shell → ConsumerConnect input; start4. Producer → Kernel pipeWrite bytes5. Kernel pipe → ConsumerRead bytes6. Kernel pipe → ConsumerEOF after writers close
The shell connects producer and consumer descriptors through a finite kernel pipe.
02

Plan five scripting answers before typing

5 min read

For each timed task, state the shell, input format, output format and failure meanings. Reserve time for one ordinary case, one boundary and one failure. Explain commands before running them. The interview rewards a correct limited solution more than an unexplained chain of commands.

1Parse a log with a declared format

Suppose a fixture has exactly three whitespace-separated fields: timestamp, client IP address and status code. An IP address identifies a network interface at the Internet Protocol layer. The fixture is a learning format, not a claim about every web or SSH log.

Generate the fixture before demonstrating a parser:

bash
printf '%s\n' \
  '2026-11-17T10:00:00Z 192.0.2.10 200' \
  '2026-11-17T10:00:01Z 192.0.2.11 503' \
  '2026-11-17T10:00:02Z 192.0.2.11 500' > access.fixture

These are synthetic input records using documentation addresses. A parser can require three fields and a three-digit status, count rejected lines, and select server errors from 500 through 599. That validates the fixture's shape, not full timestamp or IP syntax. Explain which validation your real application requires.

For system logs, first inspect the actual source. Ubuntu text syslog can use an ISO timestamp as one field. A journal stores structured fields and is queried with journalctl. Do not apply an old three-field timestamp assumption to either source blindly.

2Find the top N client addresses

Describe two approaches. Sort addresses, count adjacent equal values, then sort counts numerically. Alternatively, an awk associative array maps each address string to its count. An associative array stores values under keys rather than only numeric positions.

Validate N as a bounded positive decimal. Define deterministic tie ordering, for example count descending then address ascending under LC_ALL=C. This locale setting makes text ordering use the C locale. Avoid a full sort in a tight board memory budget without considering its temporary storage and input size.

An array uses memory proportional to the number of distinct addresses. External sorting can spill data to disk, adding storage traffic. A repeated address is not proof of one person: proxies and address sharing affect interpretation.

3Check disk usage without confusing failure and health

For the disk task, use df -P / to request a predictable POSIX-style layout for the root filesystem. Check its status before parsing its percentage. Remove the percent sign only after validating the field. Compare against the agreed threshold and return separate outcomes for healthy, warning and unable to check.

Percent used alone cannot predict a large backup's success. Also check free bytes, inode availability and the destination mount. A missing mount can make a backup fill the underlying root directory. Repeat checks immediately before writing, while recognising that other writers can consume space afterward.

4Rotate backups by completion state

Rotation means removing old backups according to a retention policy. First define "old": completion time, successful generation count or an explicit calendar rule. Write into a unique temporary location. Verify the archive and a restore, then publish a completed generation. Prune only completed generations after a new good backup exists.

Use a lock to prevent overlapping runs. Store the lock outside directories being renamed or pruned. Validate the configured backup root and generate deletion candidates within it. Use argument-safe filename handling; do not parse ls output. Preview the selected candidates before allowing deletion in the disposable lab.

Explain interruption at every boundary. A partial backup must not become the newest good copy. A filesystem rename can publish a name atomically on that filesystem, but persistence after power loss needs additional care. The backup design section returns to this distinction.

5Design a getopts CLI

Your interface should make mistakes easy to diagnose. For a practice report command, define -n N, -f FILE, -h, and no positional arguments. This skeleton demonstrates option handling; report generation is deliberately left for practice.

bash
#!/bin/bash
n=5
input=
usage() { printf '%s\n' 'Usage: report -f FILE [-n N]'; }
bad_usage() { usage >&2; exit 2; }
while getopts ':n:f:h' opt; do
    case "$opt" in
        n) n=$OPTARG ;;
        f) input=$OPTARG ;;
        h) usage; exit 0 ;;
        :) printf 'Missing value: -%s\n' "$OPTARG" >&2; bad_usage ;;
        \?) printf 'Unknown option: -%s\n' "$OPTARG" >&2; bad_usage ;;
    esac
done
shift "$((OPTIND - 1))"
(( $# == 0 )) || bad_usage
[[ $n =~ ^[1-9][0-9]{0,2}$ ]] || bad_usage
[[ -n $input && -f $input && -r $input ]] || bad_usage

The leading colon requests explicit error handling. Colons after n and f require values. OPTARG holds the option value or offending option; OPTIND tracks the next argument. The bound avoids oversized arithmetic inputs and leading-zero ambiguity. Reset OPTIND=1 if parsing again in the same shell context.

The readability check can race with a later open; handle the actual read failure too. Bash's [[ ... ]], regex matching and arithmetic commands are not POSIX sh syntax. On a BusyBox target, either require Bash or implement and test a supported sh version.

Plan before typingDeclareinputShell,format andlimitsValidateRejectunsupportedvaluesBound workMemory,time andsideeffectsReportoutcomeSeparatefailurefrom healthCheckboundariesNormal,edge andfailurecasesDeclareinputShell,format andlimitsValidateRejectunsupportedvaluesBound workMemory,time andsideeffectsReportoutcomeSeparatefailurefrom healthCheckboundariesNormal,edge andfailurecases
Each scripting task moves through an input definition, validation, bounded work and observable result.

Key takeaways

  • Signals request actions; SIGKILL removes user-space cleanup and may wait on kernel work.
  • State log formats, shell assumptions, error meanings and retention rules before writing a script.
  • A pipeline connects descriptors with finite kernel buffering, so set pipefail and treat SIGPIPE as early exit rather than always lost data
  • Treat a failed probe as unknown, not healthy, and return a distinct failure outcome
Reflect
  1. Explain to a colleague, in two sentences: apply shell parsing, validation and failure handling to five timed scripting scenarios.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

Find your next step

↑ ↓ to move · Enter to open · Esc to close