UNIX Operating System - Complete Exam Answers
Question No. 1
a) UNIX Architecture
UNIX follows a layered architecture with four main components:
1. Hardware Layer
Physical components: CPU, memory, disk drives, terminals
Foundation of the entire system
2. Kernel
Core of UNIX operating system
Manages system resources (CPU, memory, I/O devices)
Provides system calls interface
Handles process management, file system, device drivers
Runs in privileged mode
3. Shell
Command interpreter and user interface
Acts as intermediary between user and kernel
Provides command-line interface
Executes user commands and programs
4. Applications/Utilities
User programs and system utilities
Text editors, compilers, system administration tools
User-written applications
b) Features of UNIX Operating System
1. Multi-user System
Multiple users can work simultaneously
Each user has separate workspace and permissions
2. Multi-tasking
Can execute multiple processes concurrently
Time-sharing implementation
3. Portability
Written in C language
Can run on different hardware platforms
4. Hierarchical File System
Tree-like directory structure
Root directory (/) at the top
5. Shell Programming
Command interpreter with programming capabilities
Script automation possible
6. Pipes and Filters
Output of one command can be input to another
Powerful text processing capabilities
7. Security
User authentication and file permissions
Access control mechanisms
8. Utilities
Rich set of built-in commands and utilities
Question No. 2
a) Process Creation in UNIX
Process Creation Steps:
1. fork() System Call
Creates exact copy of parent process
Returns PID of child to parent, 0 to child
c
pid_t pid = fork();
if (pid == 0) {
// Child process
} else if (pid > 0) {
// Parent process
}
2. exec() System Call
Replaces current process image with new program
Various forms: execl(), execv(), execp()
3. Process States
Ready: Waiting for CPU
Running: Currently executing
Blocked: Waiting for I/O or event
Zombie: Terminated but not cleaned up
b) Shell Creation in UNIX
Shell Creation Process:
1. System Initialization
init process (PID 1) starts
Reads /etc/inittab for configuration
2. Login Process
getty process waits for login
Prompts for username/password
3. Authentication
login program verifies credentials
Checks /etc/passwd file
4. Shell Startup
exec() system call loads shell program
Shell inherits user environment
Reads initialization files (.profile, .bashrc)
Question No. 3
a) Hard Link and Soft Link
Hard Link:
Direct reference to inode
Same inode number as original file
Cannot cross file systems
Cannot link to directories
File exists until all hard links removed
bash
ln file1 hardlink1
Soft Link (Symbolic Link):
Pointer to filename/path
Different inode number
Can cross file systems
Can link to directories
Broken if original file deleted
bash
ln -s file1 softlink1
b) Functions of System Administrator
1. User Management
Create/delete user accounts
Manage passwords and permissions
User group administration
2. System Maintenance
System updates and patches
Performance monitoring
Backup and recovery
3. Security Management
Access control implementation
Security policy enforcement
Audit trail monitoring
4. File System Management
Disk space monitoring
File system creation/mounting
Permission management
5. Process Management
Monitor system processes
Kill runaway processes
Resource allocation
Question No. 4
a) Different Types of Files in UNIX
1. Regular Files (-)
Text files, binary files, executable files
Store data and programs
2. Directory Files (d)
Special files containing file lists
Organize file system structure
3. Character Device Files (c)
Provide unbuffered access to hardware
Examples: terminals, printers
4. Block Device Files (b)
Provide buffered access to hardware
Examples: hard disks, CD-ROMs
5. Named Pipes (p)
FIFO (First In, First Out) files
Inter-process communication
6. Socket Files (s)
Network communication endpoints
7. Symbolic Links (l)
Pointers to other files
b) Different File Systems in UNIX
1. UFS (UNIX File System)
Traditional UNIX file system
Hierarchical structure with inodes
2. NFS (Network File System)
Distributed file system
Remote file access over network
3. ext2/ext3/ext4
Extended file systems for Linux
Journaling capabilities in ext3/ext4
4. ZFS (Zettabyte File System)
Advanced file system with built-in volume management
Data integrity and compression features
5. XFS
High-performance journaling file system
Scalable for large files and file systems
c) Environment Variables in UNIX
Common Environment Variables:
1. HOME - User's home directory path
2. PATH - Command search path
3. SHELL - Current shell program
4. USER/USERNAME - Current user name
5. PWD - Present working directory
6. OLDPWD - Previous working directory
7. PS1 - Primary shell prompt
8. TERM - Terminal type
9. LANG - Language and locale settings
10. LD_LIBRARY_PATH - Library search path
bash
# View environment variables
env
echo $HOME
export MYVAR="value"
Question No. 5 - Short Notes
GREP Command
Purpose: Global Regular Expression Print
Function: Search text patterns in files
Syntax: grep [options] pattern file(s)
Examples:
bash
grep "error" logfile.txt
grep -i "Error" file.txt # case insensitive
grep -v "debug" file.txt # invert match
grep -n "pattern" file.txt # show line numbers
VI Editor
Purpose: Visual text editor
Modes:
Command mode: Navigation and commands
Insert mode: Text editing
Ex mode: File operations
Basic Commands:
i - Insert mode
ESC - Command mode
:w - Save file
:q - Quit
:wq - Save and quit
dd - Delete line
yy - Copy line
LS Command
Purpose: List directory contents
Common Options:
bash
ls # basic listing
ls -l # long format with details
ls -a # show hidden files
ls -la # long format with hidden files
ls -lt # sort by modification time
ls -lh # human readable file sizes
Question No. 6
Filters in UNIX
Definition: Programs that read input, transform it, and write output.
Common Filter Commands:
1. grep - Pattern searching
2. sort - Sort lines of text
3. uniq - Remove duplicate lines
4. cut - Extract columns
5. tr - Translate characters
6. sed - Stream editor
7. awk - Pattern scanning and processing
8. head - Display first lines
9. tail - Display last lines
10. wc - Word, line, character count
Job Control in UNIX
Background Jobs:
bash
command & # Run in background
jobs # List active jobs
fg %1 # Bring job 1 to foreground
bg %1 # Send job 1 to background
kill %1 # Kill job 1
Job Control Commands:
Ctrl+Z - Suspend current job
Ctrl+C - Terminate current job
nohup - Run command immune to hangups
Purpose of & and NOHUP
& (Ampersand):
Runs command in background
Allows shell prompt to return immediately
Job continues while you work on other tasks
NOHUP:
"No hang up" - process continues after logout
Redirects output to nohup.out file
Immune to SIGHUP signal
bash
nohup long_running_script.sh &
Question No. 7
Relative and Absolute Permissions using CHMOD
Absolute (Octal) Method:
bash
chmod 755 file # rwxr-xr-x
chmod 644 file # rw-r--r--
chmod 600 file # rw-------
Permission Values:
Read (r) = 4
Write (w) = 2
Execute (x) = 1
Relative (Symbolic) Method:
bash
chmod u+x file # Add execute for user
chmod g-w file # Remove write for group
chmod o=r file # Set others to read only
chmod a+r file # Add read for all
Symbols:
u = user (owner)
g = group
o = others
a = all
Command Purposes with Examples
CD (Change Directory):
bash
cd /home/user # Absolute path
cd Documents # Relative path
cd .. # Parent directory
cd ~ # Home directory
cd - # Previous directory
MKDIR (Make Directory):
bash
mkdir newdir # Create single directory
mkdir -p dir1/dir2/dir3 # Create nested directories
mkdir dir1 dir2 dir3 # Create multiple directories
RM (Remove):
bash
rm file.txt # Remove file
rm -i file.txt # Interactive removal
rm -r directory # Remove directory recursively
rm -f file.txt # Force removal
CP (Copy):
bash
cp file1 file2 # Copy file
cp file1 /path/ # Copy to directory
cp -r dir1 dir2 # Copy directory recursively
cp -i file1 file2 # Interactive copy
Question No. 8 - Command List
Directory Operation Commands:
1. Display pathname of current directory:
bash
pwd
2. Changing current directory:
bash
cd /path/to/directory
3. Create directory:
bash
mkdir directory_name
4. Remove directory:
bash
rmdir empty_directory # Remove empty directory
rm -r directory # Remove directory with contents
5. Listing directory including hidden files:
bash
ls -a
6. List files with inode numbers:
bash
ls -i
7. Change to home directory:
bash
cd ~
cd $HOME
cd
8. Move to parent directory:
bash
cd ..
9. Get detailed directory information:
bash
ls -l # Long format
ls -la # Long format with hidden files
stat directory_name # Detailed file statistics
Question No. 11
a) Mounting and Unmounting
Mounting:
Process of making file system accessible
Attaches file system to directory tree
bash
mount /dev/sda1 /mnt/usb # Mount device
mount -t ext4 /dev/sda1 /mnt # Specify file system type
mount -o ro /dev/cdrom /mnt # Mount read-only
Unmounting:
Detaching file system from directory tree
Ensures data integrity
bash
umount /mnt/usb # Unmount by mount point
umount /dev/sda1 # Unmount by device
b) Zombie and Daemon Processes
Zombie Process:
Terminated process with entry in process table
Parent hasn't read exit status
Takes minimal system resources
Cleaned up when parent reads exit status
Daemon Process:
Background process running continuously
No controlling terminal
Provides system services
Examples: httpd, sshd, cron
Quoting and Escaping
Single Quotes (''):
Preserve literal value of all characters
No variable expansion
Double Quotes (""):
Allow variable expansion
Preserve most special characters
Backslash ():
Escape single character
Remove special meaning
bash
echo 'The $HOME directory' # Literal $HOME
echo "The $HOME directory" # Expands $HOME
echo The \$HOME directory # Escaped $HOME
Question No. 12
a) Regular Expressions
Basic Regular Expressions (BRE):
Used by grep, sed, vi
Metacharacters: . * ^ $ [ ] \
Extended Regular Expressions (ERE):
Used by egrep, awk
Additional metacharacters: + ? | ( ) { }
Common Patterns:
bash
^pattern # Beginning of line
pattern$ # End of line
. # Any single character
* # Zero or more of preceding
+ # One or more of preceding (ERE)
? # Zero or one of preceding (ERE)
[abc] # Character class
[^abc] # Negated character class
b) Inode Structure
Inode (Index Node):
Data structure storing file metadata
Contains file attributes, not filename
Inode Contents:
File type and permissions
Number of hard links
Owner UID and GID
File size
Timestamps (access, modify, change)
Pointers to data blocks
Block count
c) Standard I/O
Standard Input (stdin) - File descriptor 0:
Default input source (keyboard)
Can be redirected with <
Standard Output (stdout) - File descriptor 1:
Default output destination (screen)
Can be redirected with >
Standard Error (stderr) - File descriptor 2:
Error message output (screen)
Can be redirected with 2>
bash
command < input.txt # Redirect input
command > output.txt # Redirect output
command 2> error.txt # Redirect errors
command > out.txt 2>&1 # Redirect both
Question No. 13
AT and BATCH Commands
AT Command:
Schedule job for specific time
One-time execution
bash
at 15:30 # Schedule for 3:30 PM
at now + 1 hour # Schedule for 1 hour later
at midnight # Schedule for midnight
BATCH Command:
Schedule job when system load is low
Executes when load average drops
bash
batch # Schedule batch job
TEST Command
Purpose: Evaluate conditional expressions in shell scripts
Syntax: test expression or [ expression ]
Examples:
bash
test -f file.txt # Check if file exists
[ -d directory ] # Check if directory exists
test $a -eq $b # Compare numbers
[ "$str1" = "$str2" ] # Compare strings
UNIX Run Levels
Run Levels: 0. Halt/Shutdown
1. Single-user mode
2. Multi-user mode without networking
3. Multi-user mode with networking
4. Unused/User-defined
5. Multi-user mode with GUI
6. Reboot
Question No. 14 - Shell Scripts
A) Prime Numbers Between 1 to N
bash
#!/bin/bash
echo "Enter a number:"
read n
echo "Prime numbers between 1 and $n:"
for ((i=2; i<=n; i++))
do
flag=1
for ((j=2; j<=i/2; j++))
do
if [ $((i % j)) -eq 0 ]
then
flag=0
break
fi
done
if [ $flag -eq 1 ]
then
echo $i
fi
done
B) Fibonacci Series
bash
#!/bin/bash
echo "Enter number of terms:"
read n
a=0
b=1
echo "Fibonacci Series:"
echo $a
echo $b
for ((i=2; i<n; i++))
do
c=$((a + b))
echo $c
a=$b
b=$c
done
C) Armstrong Number
bash
#!/bin/bash
echo "Enter a number:"
read num
temp=$num
sum=0
while [ $temp -gt 0 ]
do
digit=$((temp % 10))
sum=$((sum + digit * digit * digit))
temp=$((temp / 10))
done
if [ $sum -eq $num ]
then
echo "$num is an Armstrong number"
else
echo "$num is not an Armstrong number"
fi
D) Check if Number is Palindrome
bash
#!/bin/bash
echo "Enter a number:"
read num
temp=$num
rev=0
while [ $temp -gt 0 ]
do
digit=$((temp % 10))
rev=$((rev * 10 + digit))
temp=$((temp / 10))
done
if [ $rev -eq $num ]
then
echo "$num is a palindrome"
else
echo "$num is not a palindrome"
fi
E) Reverse of a Number
bash
#!/bin/bash
echo "Enter a number:"
read num
rev=0
while [ $num -gt 0 ]
do
digit=$((num % 10))
rev=$((rev * 10 + digit))
num=$((num / 10))
done
echo "Reversed number: $rev"
F) Check File Permissions
bash
#!/bin/bash
echo "Enter filename:"
read filename
if [ -r "$filename" ]
then
echo "File is readable"
else
echo "File is not readable"
fi
if [ -w "$filename" ]
then
echo "File is writable"
else
echo "File is not writable"
fi
if [ -x "$filename" ]
then
echo "File is executable"
else
echo "File is not executable"
fi
Question No. 15
A) Different Blocks of UNIX
1. Boot Block:
First block of file system
Contains bootstrap program
Loads operating system
2. Super Block:
Contains file system metadata
File system size, free blocks
Inode table information
3. Inode Table:
Array of inodes
File metadata storage
Fixed size per file system
4. Data Blocks:
Actual file content storage
Directory entries
User data
B) Home Directory
Definition: Default directory assigned to user at login
Characteristics:
Personal workspace for user
Contains user files and subdirectories
Path stored in $HOME variable
Usually /home/username or /Users/username
C) Root Directory
Definition: Top-level directory in UNIX file system hierarchy
Characteristics:
Represented by forward slash (/)
Parent of all directories
Contains system directories like /bin, /etc, /usr
Root user's home directory often /root
SU and SU Commands
SU (Switch User):
bash
su # Switch to root user
su username # Switch to specific user
su - # Switch with environment reset
SU ROMEO:
bash
su romeo # Switch to user 'romeo'
Question No. 16
MAN and CAT Commands
MAN Command:
Manual pages for commands
Documentation system
bash
man ls # Manual for ls command
man 5 passwd # Section 5 of passwd manual
man -k keyword # Search manual pages
CAT Command:
Display file contents
Concatenate files
bash
cat file.txt # Display file
cat file1 file2 # Concatenate files
cat > newfile.txt # Create new file
PID and PPID
PID (Process ID):
Unique identifier for each process
Assigned by kernel when process created
PPID (Parent Process ID):
PID of parent process
Shows process hierarchy
bash
ps -ef # Show PID and PPID
echo $$ # Current shell PID
Absolute and Relative Pathname
Absolute Pathname:
Complete path from root directory
Starts with forward slash (/)
Example: /home/user/documents/file.txt
Relative Pathname:
Path relative to current directory
Does not start with /
Example: documents/file.txt, ../parent_dir
Different Types of Shells
1. Bourne Shell (sh):
Original UNIX shell
Basic scripting capabilities
2. C Shell (csh):
C-like syntax
Command history and aliases
3. Korn Shell (ksh):
Enhanced Bourne shell
Command line editing
4. Bash (Bourne Again Shell):
GNU enhancement of Bourne shell
Popular on Linux systems
5. Zsh (Z Shell):
Extended features
Advanced completion
Question No. 17
Difference between ls commands
(i) ls -l vs ls -lt:
ls -l:
Long format listing
Shows permissions, links, owner, group, size, date
Default alphabetical order by filename
ls -lt:
Long format listing sorted by modification time
Most recently modified files first
Same information as ls -l but different order
(ii) ls -lu vs ls -lut:
ls -lu:
Long format with access time instead of modification time
Shows when files were last accessed
Alphabetical order by filename
ls -lut:
Long format with access time
Sorted by access time (most recently accessed first)
Combines -u (access time) and -t (time sort)
Question No. 18
EGREP and GREP -E
EGREP:
Extended grep
Supports Extended Regular Expressions (ERE)
Same as grep -E
GREP -E:
Enables extended regular expressions in grep
Supports additional metacharacters: +, ?, |, (), {}
Examples:
bash
egrep "pattern1|pattern2" file.txt # OR operation
grep -E "pattern1|pattern2" file.txt # Same as above
egrep "colou?r" file.txt # Optional 'u'
grep -E "[0-9]+" file.txt # One or more digits
Extended Features:
+ : One or more occurrences
? : Zero or one occurrence
| : Alternation (OR)
() : Grouping
{} : Specific repetition counts