Unix and Shell Programming
Comprehensive exam revision notes for BCA-204N Unit 1 (Unix Architecture, Commands & Process Management). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.
Unix and Shell Programming
Unix Architecture, Commands & Process Management
Core Definitions & Key Concepts
What are the four primary layers of the Unix Operating System architecture
The four layers from inner to outer are:
- Hardware: Physical CPU, memory, disks.
- Kernel: Core managing hardware, memory, files, and scheduling.
- Shell: Command-line interpreter mediating between user and kernel.
- Utilities & Applications: Standard tools (
ls,grep, compilers).
What is the primary role of the Unix Kernel
The Kernel is the master control program that executes in privileged supervisor mode. It manages CPU process scheduling, physical/virtual memory allocation, file systems, device I/O drivers, and handles system calls.
cat and more/less commands
cat concatenates and dumps entire file contents onto terminal without pausing. more and less are pagers that display file contents screen-by-screen, with less allowing backward scrolling.
What is the difference between an internal command and an external command in Unix
- Internal (Built-in): Built directly into the shell binary (e.g.,
cd,pwd,echo,exit); executes immediately without spawning child processes. - External: Standalone executable binaries residing on disk (e.g.,
/bin/ls,/usr/bin/grep); shell forks a child process to execute them.
What is a Process ID (PID) and Parent Process ID (PPID)
- PID: Unique positive integer assigned by the kernel to identify an active process.
- PPID: The PID of the parent process that spawned this process using the
fork()system call.
What is a Zombie Process in Unix
A zombie (defunct) process is one that has terminated its execution via exit(), but whose entry remains in the process table because its parent has not yet read its exit status code via wait().
What is an Orphan Process, and how does Unix handle it
An orphan process is an active process whose parent process terminated or crashed before it. The Unix `init` process (PID 1) automatically adopts all orphan processes and reaps their exit status upon termination.
What does the nohup command do
nohup (no hangup) runs a command immune to SIGHUP (signal 1) disconnections, allowing background jobs to continue running even after the user logs out.
Conceptual & Architectural Analysis
The Unix Process Life Cycle and State Transitions with a State Diagram
Unix Process State Transitions
[ Created via fork() ]
|
v
+-----------------------------------+
| Ready-to-Run |
| (in memory or swapped) |
+-----------------------------------+
^ |
Preempted | | Scheduled (CPU Dispatch)
| v
+-----------------------------------+
| Kernel / User |
| Running Mode |
+-----------------------------------+
^ |
Event | | Sleep / Wait (I/O, Semaphore)
Occurs | v
+-----------------------------------+
| Asleep |
| (Blocked on I/O) |
+-----------------------------------+
|
Process Terminates (exit)
v
+-----------------------------------+
| Zombie / Defunct |
| (Waiting for parent wait) |
+-----------------------------------+- Running: Process is executing on CPU (User or Kernel mode).
- Ready: Process has all resources and is waiting in run queue for CPU slice.
- Blocked/Asleep: Waiting for I/O completion or signal.
- Zombie: Process terminated, awaiting parent
wait()cleanup.
The Process Creation Mechanism using fork(), exec(), and wait() System Calls
Process Creation Pipeline
- `fork()`: Clones the calling process, creating an exact child replica with duplicate address space. Returns
0to child and child's PID to parent. - `exec()` family: Replaces the child's memory image, stack, and text segment with a new program binary from disk.
- `wait()` / `waitpid()`: Parent process suspends execution until the child finishes, obtaining termination status and clearing zombie entries.
Process Scheduling Priority and the nice / renice Commands
Unix processes have a priority value calculated from CPU utilization and a nice value (range -20 to +19):
- Default nice value is
0. - Higher positive nice value (+19) makes the process 'nicer' (lower CPU priority).
- Negative nice values (-20) grant highest priority (requires root).
nice -n 10 ./compute_heavy.sh: Launches job with lower priority.renice +5 -p 1420: Dynamically alters priority of running PID 1420.
Compare ps Options and Common Signals used with the kill Command
| Command / Signal | Code | Action |
|---|---|---|
ps -ef / ps aux | - | Displays full listing of all active processes across all users |
| SIGHUP | 1 | Hangup signal sent when terminal closes |
| SIGINT | 2 | Interrupt signal sent by user pressing Ctrl+C |
| SIGKILL | 9 | Uncatchable, unignorable immediate termination by kernel |
| SIGTERM | 15 | Polite, graceful termination signal (default for kill) |
| SIGSTOP | 19 | Uncatchable signal that pauses process (Ctrl+Z sends SIGTSTP) |
In-Depth Analysis & Implementation
Write a Complete C Program in Unix Demonstrating fork(), getpid(), getppid(), and Parent-Child Synchronization
1/**2 * University Model Solution: BCA-204N Unit 13 * Process Management using Unix System Calls4 */5#include <stdio.h>6#include <stdlib.h>7#include <unistd.h>8#include <sys/types.h>9#include <sys/wait.h>10
11int main() {12 pid_t pid;13 int status;14
15 printf("[Parent] Master Process Started. PID: %d, PPID: %d\n", getpid(), getppid());16
17 // Fork child process18 pid = fork();19
20 if (pid < 0) {21 perror("fork failed");22 exit(EXIT_FAILURE);23 } else if (pid == 0) {24 // Child Process25 printf(" [Child] Running! Child PID: %d, Parent PPID: %d\n", getpid(), getppid());26 printf(" [Child] Performing computation work for 2 seconds...\n");27 sleep(2);28 printf(" [Child] Task complete. Exiting with status code 42.\n");29 exit(42);30 } else {31 // Parent Process32 printf("[Parent] Spawned Child with PID: %d. Waiting for child to terminate...\n", pid);33 34 // Wait for child35 pid_t terminated_child = wait(&status);36 37 if (WIFEXITED(status)) {38 int exit_code = WEXITSTATUS(status);39 printf("[Parent] Child PID %d successfully reaped. Exit Code: %d\n", 40 terminated_child, exit_code);41 }42 printf("[Parent] All tasks finished. Exiting.\n");43 }44 return 0;45}Standard Unix Command-Line Navigation, File Manipulation, and Piping with Examples
Fundamental Unix Command-Line Mastery
# 1. Directory Navigation and Inspection
pwd # Print Current Working Directory
ls -lahr /var/log # Long list, all hidden files, human sizes, reverse time sort
cd ~ # Change to user home directory
# 2. File and Directory Operations
mkdir -p project/{src,bin,docs} # Nested directory hierarchy creation
cp -rv ./src/ /backup/src/ # Recursive verbose copy
mv old_name.txt new_name.txt # Rename or move file
rm -rf /tmp/scratch_dir/ # Force recursive removal
# 3. Viewing and Searching Content
cat -n file.txt # Display file with line numbers
head -n 20 access.log # View first 20 lines
tail -n 50 -f /var/log/syslog # Follow live appended log stream in real time
# 4. Process Inspection and Control
ps -ef | grep "python" # Find all running python processes
kill -15 2401 # Request graceful termination of PID 2401
kill -9 2401 # Force kill PID 2401 if hung
# 5. Background Jobs
sleep 100 & # Run command in background
jobs # List active terminal background jobs
fg %1 # Bring job 1 to foregroundThe Architecture and Design Philosophy of the Unix Operating System in Depth
The Unix Philosophy and Architecture
Formulated by Ken Thompson, Dennis Ritchie, and Doug McIlroy at Bell Labs:
- Everything is a File: Hardware devices (
/dev/sda), network sockets, terminals (/dev/pts/0), and directories are exposed through unified standard file descriptor APIs (open,read,write,close). - Small is Beautiful: Write small, modular programs that do exactly one task and do it exceptionally well.
- Composability via Pipes: Connect output of one program directly into input of another using standard textual byte streams (
stdin,stdout). - Portability: Written in high-level C language rather than assembly, allowing Unix to be ported across diverse CPU architectures.
- Kernel-Shell Separation: User interface logic is strictly separated from kernel privilege mode, preventing user crashes from bringing down the OS kernel.
Important Exam Points & Quick Revision
Master the difference between fork() and exec(), zombie vs orphan process creation, and signal codes (SIGKILL vs SIGTERM).
100% left on this page — finishing it closes the gap for Unix Architecture, Commands & Process Management.
Unix Architecture, Commands & Process Management still counts as a weak topic until you finish this note and answer its questions.
Practise this unitTest Your Understanding
Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.