0% found this document useful (0 votes)
14 views35 pages

Operating Systems and Linux Programming Guide

Uploaded by

gururajsingh777
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views35 pages

Operating Systems and Linux Programming Guide

Uploaded by

gururajsingh777
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Course Code BCA

Course Name: Operating System & Linux Programming

UNIT–I

1. Introduction: What is an Operating System?


An Operating System (OS) is system software that acts as an intermediary between the user
and the computer hardware.
It manages hardware resources and provides services to applications.
Definition (Write this in exam):
An Operating System is a program that manages the hardware of a computer, provides an
environment for application programs to run, and acts as a bridge between the user and
hardware.
In simple words:
OS = Manager of all computer activities
OS = Controls everything happening inside the computer.
Examples: Windows, Linux, macOS, Android, iOS.

✅ 2. Functions of an Operating System


The OS performs many important tasks. The main functions include:
1. Process Management
 A process = a running program.
 OS creates, schedules, and terminates processes.
 It ensures CPU is efficiently used.
 Uses scheduling algorithms (FCFS, Round Robin etc.)
2. Memory Management
 Allocates memory to processes.
 Keeps track of used/free memory.
 Handles swapping, paging, segmentation.
3. File Management
 Manages files on storage devices.
 Directory structure, permissions, file operations (create, delete, read, write).
4. Device Management
 Controls hardware devices using device drivers.
 Manages I/O operations (keyboard, printer, disk).
5. Storage Management
 Handles data storage on HDD/SSD.
 Responsible for disk scheduling, free-space management.
6. Security and Protection
 Provides user authentication (passwords).
 Prevents unauthorized access.
 Protects memory and files from misuse.
7. User Interface
 Provide either:
o CLI – Command Line Interface
o GUI – Graphical User Interface (Windows style)

✅ 3. Simple Batch Systems


Meaning:
Early computers used batch processing, where jobs were collected, grouped into batches, and
run without user interaction.
Key Points:
 Users submit jobs on punch cards.
 Jobs run one after another.
 No interaction with program during execution.
 Better throughput than manual operation.
Advantages:
 Efficient for long jobs.
 Minimal idle time.
Disadvantages:
 No multitasking.
 No priority handling.
 Long waiting time for users.

✅ 4. Multiprogrammed Batch Systems


Meaning:
Improved version of simple batch systems.
Multiple jobs are kept in memory at the same time.
When one job waits for I/O, the CPU switches to another job.
Purpose:
To increase CPU utilization.
Working:
1. OS loads several jobs.
2. CPU executes one job.
3. If job is waiting for I/O → CPU shifts to next job.
4. This overlap of CPU + I/O increases efficiency.
Advantages:
 High CPU usage.
 Faster processing.
Disadvantages:
 Needs complex OS.
 Requires memory management.

✅ 5. Time-Sharing Systems (or Multitasking Systems)


Idea:
Many users can interact with the computer simultaneously.
How?
 CPU time is divided into time slices.
 Each user/program gets a small time slice.
 Rapid switching makes it appear that programs run in parallel.
Examples:
University computer labs, Unix/Linux servers.
Advantages:
 Fast response time.
 Good for interactive tasks.
Disadvantages:
 High overhead for context switching.
 Needs proper scheduling.

✅ 6. Personal-Computer Systems
Meaning:
These are general-purpose OS used on personal devices like laptops and desktops.
Examples:
 Windows
 macOS
 Linux (Ubuntu)
Characteristics:
 User-friendly GUI
 Support for multimedia
 Good security features
 Support single user but multitasking
These systems are optimized for performance, usability, and security.

✅ 7. Parallel Systems (or Multiprocessor Systems)


Meaning:
Systems with multiple CPUs working together.
Goal:
To improve speed, performance, and reliability.
Types:
1. Symmetric Multiprocessing (SMP)
o All processors use the same memory and perform tasks equally.
2. Asymmetric Multiprocessing (AMP)
o One main processor controls others.
Advantages:
 Faster execution.
 High reliability (if one CPU fails, others continue).
Disadvantages:
 Expensive.
 Requires special OS support.

✅ 8. Distributed Systems
Meaning:
A distributed system is a collection of independent computers connected via a network that
work together.
Examples:
 Google Cloud
 Banking networks
 Internet-based systems
Characteristics:
 Share resources using networking.
 Offer distributed computing and storage.
Advantages:
 High reliability.
 Scalability.
 Resource sharing.
Disadvantages:
 Network dependency.
 Security challenges.
✅ 9. Real-Time Systems
Meaning:
Systems that require immediate or guaranteed response.
These are used in environments where delay can cause failure.
Types:
1. Hard Real-Time Systems
o Missing deadline = system failure.
o Example: Aircraft control, medical systems.
2. Soft Real-Time Systems
o Missing deadline is tolerable but undesirable.
o Example: Video streaming, online gaming.
Characteristics:
 Fast response.
 Predictable timing.
 High reliability.

✅ INTRODUCTION TO LINUX
✅ 1. Architecture of Linux Operating System
Linux architecture is usually explained in 5 layers:
1. Hardware Layer
 This includes the physical components of your computer – CPU, RAM, Hard disk,
Keyboard, Mouse, etc.
 Linux interacts with hardware through the kernel.
2. Kernel
 The core of the Linux OS.
 Controls hardware.
 Manages processes, memory, file systems, input/output devices.
 Example: When you open a program, the kernel gives it memory and CPU time.
3. System Libraries
 These are special functions/programs used by applications to communicate with
the kernel.
 Examples include standard C library (glibc).
4. System Utilities
 Basic programs that perform common tasks.
 Examples: ls, cp, mv, mkdir.
5. Applications
 User-level programs such as browsers, text editors, and media players.
✅ Simple Diagram (Exam Friendly)
+--------------------+
| Applications |
+--------------------+
| System Utilities |
+--------------------+
| System Libraries |
+--------------------+
| Kernel |
+--------------------+
| Hardware |
+--------------------+

✅ 2. Basic Directory Structure of Linux (Filesystem Hierarchy)


Linux has a tree-like directory structure starting from the root /.
Important Directories
✅ Remember:
Windows uses drive letters (C:, D:)
Linux uses one single tree starting from /.

✅ 3. Basic Linux Commands (with simple explanations)


✅ Directory Navigation Commands

✅ File and Directory Operations


✅ System Information Commands
✅ VI EDITOR
The vi editor is a powerful text editor in Linux.
✅ Three Modes of vi Editor
1. Command Mode (Default)
 For navigation and commands.
 Press Esc to enter command mode anytime.
2. Insert Mode
 For typing text.
 Press i to enter insert mode.
3. Last Line Mode (Command Line Mode)
 For saving, quitting, searching.
 Press : to enter this mode.

✅ Basic vi Commands
UNIT–II
UNIT: PROCESSES
1. Process Concept
✅ What is a Process?
A process is a program that is currently being executed.
A program is only a passive set of instructions stored on disk (e.g., a .c file, .exe file).
A process is an active entity that:
 has been loaded into memory,
 has resources allocated (CPU time, memory, I/O),
 is being scheduled/executed by the operating system.
✅ Main Components of a Process
Every process has:
1. Program Code → also called text section.
2. Data Section → global variables, static variables.
3. Heap → grows during execution when memory is allocated dynamically
(malloc/new).
4. Stack → stores function calls, local variables, return addresses.
5. Process Control Block (PCB) → the most important part (explained next).

Process Control Block (PCB)


✅ What is PCB?
The OS keeps information about each process inside a PCB.
✅ PCB contains:
 Process ID (PID)
 Process State (new, ready, running, waiting, terminated)
 Program Counter (next instruction address)
 CPU Registers
 Memory info (base/limit registers, page tables)
 Open files
 Scheduling information (priority, wait time, etc.)
PCB helps the OS manage processes and switch between them.

2. Process States
A process moves through several states:
1. New – process created.
2. Ready – waiting to get CPU.
3. Running – currently using CPU.
4. Waiting/Blocked – waiting for I/O or event.
5. Terminated – finished execution.
6. Ready Suspended / Blocked Suspended (in some OSs).

3. Process Scheduling
The OS decides which process gets the CPU next.
✅ Why is scheduling needed?
 Only one process can run on a CPU at a time (in uni-core).
 Others must wait.
 The goal: maximize CPU utilization, minimize waiting time.

✅ PROCESS SCHEDULING ALGORITHMS


1. First Come First Serve (FCFS)
 Queue-based
 Process that comes first is executed first.
 Non-preemptive (cannot be interrupted).
 Simple but suffers from convoy effect.

2. Shortest Job First (SJF)


 Selects process with shortest CPU burst.
 Can be preemptive (SRTF) or non-preemptive.
 Optimal in theory, but needs prediction of CPU burst time.
3. Priority Scheduling
 Each process assigned a priority number.
 CPU is given to highest priority.
 Can be preemptive or non-preemptive.
 Problem: Starvation → solved by aging.

4. Round Robin (RR)


 Very important in OS exams.
 Each process gets a time slice (quantum).
 Preemptive.
 Good for time-sharing systems.
 Better response time than FCFS.

5. Multilevel Queue Scheduling


 Processes classified into queues:
o Foreground (interactive)
o Background (batch)
 Each queue has its own scheduling algorithm.
 No movement between queues.

6. Multilevel Feedback Queue


 Like multilevel queue but allows movement between queues.
 Useful for giving more CPU to short jobs.

✅ Scheduling Criteria
These help judge which algorithm is good:
1. CPU Utilization – keep CPU busy.
2. Throughput – number of processes completed per time.
3. Turnaround Time – completion time – arrival time.
4. Waiting Time – time spent in ready queue.
5. Response Time – time until first response.
6. Fairness – equal treatment.

✅ OPERATIONS ON PROCESSES
Processes are created or terminated by OS.
1. Process Creation
A process can create a child process.
Example: In UNIX
 fork() → creates child
 exec() → loads new program in process

2. Process Termination
Types:
 Normal exit – after execution completes
 Abnormal exit – error, crash
 Killed by another process – using signals
 Killed by OS – out of memory, security violation

3. Process Hierarchy
Parent and child processes form a tree-like structure.

✅ PROCESS SYNCHRONIZATION
When multiple processes run at the same time, especially sharing data, problems can occur.
1. Background
Concurrent processes may access shared data → race conditions occur.
✅ What is a Race Condition?
When multiple processes access shared data and the final result depends on the order of
execution.
2. The Critical Section Problem
✅ Critical Section:
A section of code where shared data is accessed.
Each process has:
1. Entry Section → request permission
2. Critical Section → shared data accessed
3. Exit Section
4. Remainder Section
✅ A good solution must satisfy:
1. Mutual Exclusion
Only one process in critical section at a time.
2. Progress
If no one is in the critical section, one should enter.
3. Bounded Waiting
A process should not wait forever.

✅ SEMAPHORES (Most Important)


✅ What is a Semaphore?
A integer variable that helps control access to shared resources.
Types:
 Binary Semaphore (0 or 1)
 Counting Semaphore (0…n)
Uses two atomic operations:
wait(S)
If S > 0 → S--
Else → process waits
signal(S)
S++
✅ Example: Mutual Exclusion
✅ LINUX PROCESS-RELATED COMMANDS
These are frequently asked in practical exams.

✅ 1. ps (process status)
Shows list of running processes.
Common options:
 ps → basic info
 ps -e → all processes
 ps -f → full format
 ps aux → detailed info

✅ 2. top
 Shows real-time view of processes.
 CPU, memory usage.
 Useful for monitoring performance.

✅ 3. pstree
 Shows processes in tree form (parent/child).
 Helps understand hierarchy.

✅ 4. nice
Used to start a process with a given priority.
Range: -20 (highest priority) → 19 (lowest)
Example:
nice -n 10 program
✅ 5. renice
Changes priority of an already running process.
Example:
renice -n -5 1234
Here, 1234 is PID.

✅ 6. System Calls
System calls are functions provided by OS to interact with hardware.
Examples:
 fork() – create process
 exec() – replace program
 wait() – wait for child
 exit() – terminate process
 kill() – send signal to process
System calls switch control from user mode → kernel mode.

UNIT–III

✅ MEMORY MANAGEMENT
1. Background
Memory management is the process by which an operating system (OS) handles the memory
(RAM) of a computer.
The OS must:
 Keep track of which parts of memory are in use
 Allocate memory to processes
 Deallocate memory when processes finish
 Ensure efficient and safe use of memory
Main challenges:
 Limited RAM
 Many processes need to run
 Avoiding fragmentation
 Efficient CPU–memory communication

2. Logical vs Physical Address Space


Physical Address
 Actual address in RAM hardware
 Example: 1000, 2000, 3004, etc.
Logical Address
 Generated by the CPU during program execution
 Example: 0, 4, 8, … (relative addresses)
Logical addresses are converted to physical addresses by a hardware unit called the Memory
Management Unit (MMU).
Important:
 Users/programs see logical addresses
 Hardware uses physical addresses
 Logical ≠ Physical

3. Swapping
Swapping means moving an entire process between RAM and disk.
Why swapping?
When RAM is full but more processes need memory.
How it works?
 Process P is moved to disk → RAM freed
 Later brought back into RAM
Problem: slow because disk is much slower than RAM.

4. Contiguous Allocation
Memory is allocated in one continuous block.
Two types:
a) Fixed Partitioning
 Memory divided into fixed-size blocks
 Internal fragmentation (unused space inside allocated block)
b) Dynamic Partitioning
 Memory divided at run-time as needed
 External fragmentation (free memory scattered)
Allocation strategies:
1. First-fit → first big enough space
2. Best-fit → closest-sized space
3. Worst-fit → largest free block

5. Segmentation
Memory is divided based on the logical structure of a program.
A program = segments like:
 Code segment
 Data segment
 Stack segment
 Heap segment
Each segment has:
 Segment number
 Offset (position inside segment)
Advantages:
 Logical organization
 Supports protection and sharing
Disadvantages:
 External fragmentation
 Complex management
6. Paging
Paging divides memory into fixed-size blocks:
 Page (logical)
 Frame (physical)
If page size = frame size → OS can easily map pages → frames.
Why paging?
 Avoids external fragmentation
 Simpler memory allocation
A page table maps each page to a frame.

✅ VIRTUAL MEMORY
Virtual memory allows programs to use more memory than physically available by using disk
space as extension of RAM.

1. Demand Paging
Pages are loaded into memory only when needed, not all at once.
When a needed page is not in RAM → page fault.
OS loads the missing page from disk into RAM.

2. Performance of Demand Paging


Depends on:
 Page fault rate
 Disk speed
 RAM size
 Replacement algorithm
Higher page faults → slower performance because disk access is slow.

3. Page Replacement
When RAM is full but a new page is needed:
 OS must remove an existing page
 This is page replacement
Goal: minimize page faults.

4. Page Replacement Algorithms


a) FIFO (First In First Out)
 Oldest page removed
 Simple but might remove frequently used pages
b) Optimal (OPT)
 Remove the page that will not be used for the longest time
 Theoretical; used for comparison
c) LRU (Least Recently Used)
 Remove the page that has not been used for longest time
 Good approximation of OPT
d) LFU (Least Frequently Used)
 Remove the least used page

5. Allocation of Frames
How many frames (physical pages) each process gets?
Methods:
 Equal allocation: each process gets equal frames
 Proportional allocation: based on process size
 Priority allocation: more important processes get more frames

6. Thrashing
Thrashing happens when a process spends more time swapping pages than executing
instructions.
Cause:
 Too many processes with too few frames
 Extremely high page fault rate
Solution:
 Reduce number of processes
 Increase frames
 Smart replacement

✅ DEADLOCKS
A deadlock occurs when processes are stuck waiting for each other, and none can proceed.
Example:
Process A needs resource held by B
Process B needs resource held by A
→ Both wait forever

1. System Model
Deadlock is studied using:
 Resources (printers, files, memory blocks)
 Processes request, use, and release resources

2. Deadlock Characterization
For a deadlock to occur, all 4 conditions must hold:
1. Mutual Exclusion
Only one process can use a resource at a time.
2. Hold and Wait
Process holds some resources and waits for more.
3. No Preemption
Resources cannot be forcibly taken away.
4. Circular Wait
Chain of processes waiting on each other.
If any condition is removed → deadlock cannot occur.

3. Methods of Handling Deadlocks


There are 3 main approaches:
1. Deadlock Prevention
2. Deadlock Avoidance
3. Deadlock Detection & Recovery

4. Deadlock Prevention
The idea: do not allow one of the 4 conditions to occur.
Examples:
 Do not allow hold and wait → ask processes to request all resources at once
 Preemption → forcibly take resource from a process
 Break circular wait → enforce ordering of resources

5. Deadlock Avoidance
Works only if OS knows future resource requests.
Banker’s Algorithm
 Like giving loans
 OS checks if granting a request keeps system in a safe state
 Safe state = no possibility of deadlock

6. Deadlock Detection
OS allows deadlocks to occur but detects them later.
Methods:
 Resource Allocation Graph (RAG)
 Detection algorithms
 Look for cycles

7. Recovery from Deadlock


Once detected, OS must fix it.
Methods:
a) Process Termination
 Kill one or more processes
 Simple but harsh
b) Resource Preemption
 Take resource from a process
 Rollback process state
 Try again

UNIT–IV

INFORMATION MANAGEMENT
1. Introduction to Information Management
Information Management (IM) is the process of collecting, storing, organizing, protecting, and
using information efficiently.
In computer systems, information is mainly stored as files and managed by the Operating
System (OS)—for example, Windows, Linux, or macOS.
Why Information Management is important:
 Helps users easily find and access data
 Ensures data is stored safely and securely
 Supports efficient performance and organization
 Prevents data loss
 Controls who can read or modify data
IM is closely connected to file management, storage management, data accessibility, and
security.

FILE CONCEPT
2. What is a File?
A file is a collection of related data stored on a disk.
Examples: text files, images, videos, programs, documents.
Characteristics of a file:
 Has a name
 Has a type/extension (.txt, .jpg, .exe)
 Has a location (folder/directory path)
 Has size (bytes, KB, MB)
 Has permissions (who can read/write/execute)
3. File Attributes
Files have properties managed by the OS:
 Name
 Type
 Size
 Location
 Protection (permissions)
 Timestamps (creation, modification)
 Owner (user who created the file)

FILE ACCESS METHODS


Access methods control how data in a file is read or written.
1. Sequential Access
 Data is accessed one record after another in order.
 Like reading a book from start to end.
 Used in text files and logs.
2. Direct (Random) Access
 You can jump to any part of the file directly.
 Like accessing a page in a book using the page number.
 Used in databases and large files.
3. Indexed Access
 An index is created to point to different parts of the file.
 Works like an index in the back of a book.
 Faster than sequential, simpler than random access.
 Used in large data systems.

DIRECTORY AND DISK STRUCTURE


1. Directory
A directory (or folder) is used to organize files.
Functions of a directory:
 Manages file names
 Organizes files in a tree format
 Stores metadata (size, location, type)
 Allows hierarchical structure (folders/subfolders)
Directory Structures:
1. Single-level directory
o One directory for all files
o Simple but creates name conflicts
2. Two-level directory
o One directory per user
o Avoids name conflict among users
3. Tree-structured directory
o Most common (Windows, Linux)
o Supports nested folders
4. Acyclic graph directory
o Allows shared files/folders
o Supports shortcuts/links
5. General graph directory
o More flexible but needs cycle control

2. Disk Structure
File systems manage data on disks.
Key concepts:
 Disk blocks: Files are stored in fixed-size blocks.
 File allocation table (FAT) or inode tables: Track where files are stored.
 Superblock: Contains file system information.
 Free space management: Keeps track of unused blocks.

Disk Organization Methods:


1. Contiguous Allocation
o File stored in continuous blocks
o Fast but causes fragmentation
2. Linked Allocation
o Each block points to the next block
o No fragmentation but slower for random access
3. Indexed Allocation
o Index block contains pointers to file blocks
o Efficient and supports random access

FILE PROTECTION
Files must be protected from:
 Unauthorized access
 Accidental deletion
 Modification by others
Types of File Protection:
1. Read protection – prevents viewing content
2. Write protection – prevents editing
3. Execute protection – prevents running files
4. Delete protection – prevents deletion
5. Access control – defines who can access the file
Protection uses:
 User IDs (UID)
 Group IDs (GID)
 Permissions (read/write/execute)
 Encryption (to secure data)

LINUX FILE SECURITY


Linux uses a permission-based security model.
Permission Types
Linux permissions are divided into three groups:
1. User (u) — owner of the file
2. Group (g) — users in the same group
3. Others (o) — everyone else
Each group has three permissions:

Meaning:
 Owner: rwx
 Group: r-x
 Others: r--

EXAMINING PERMISSIONS
CHANGING PERMISSIONS
Linux allows two methods:

✅ 1. Symbolic Method
Uses letters u (user), g (group), o (others), a (all).
Operations:
 + add permission
 - remove permission
 = assign exact permission
Examples:

✅ 2. Numeric (Octal) Method


Permissions have numeric values:
Examples:
 rwx = 4+2+1 = 7
 rw- = 4+2 = 6
 r-x = 4+1 = 5
 r-- = 4 = 4
Full permission is three digits:
 First digit = user
 Second digit = group
 Third digit = others
Examples:
chmod 755 [Link]
Meaning:
 User: 7 → rwx
 Group: 5 → r-x
 Others: 5 → r-x
Another example:
chmod 644 [Link]
Meaning:
 User: 6 → rw-
 Group: 4 → r--
 Others: 4 → r--
✅ SUMMARY (Quick Revision)
 File = collection of data
 Directory organizes files
 Access Methods: Sequential, Direct, Indexed
 Disk Structure: blocks, FAT/inode, allocation methods
 File Protection: permissions, access control
 Linux Permissions: read, write, execute for user/group/others
 Change permissions: chmod symbolic and numeric

You might also like