Os Lab File
Os Lab File
TECH 3 rd year
SUBJECT : OPERATING SYSTEM
SUBJECT CODE :- BT CS 605A
Submitted To : Submitted By :
Dr. Benay Kumar Ray Parmod Kumar
(211572)
Program to Simulate Bankers Algorithm for Dead Lock
Avoidance and Prevention
while True:
found = False
for i in range(num_processes):
if not finish[i] and all(need <= work for need, work in
zip(max_need[i], work)):
found = True
finish[i] = True
safe_sequence.append(i)
for j in range(num_resources):
work[j] += allocation[i][j]
break
if not found:
break
if __name__ == "__main__":
allocation = [
[0, 1, 0],
[2, 0, 0],
[3, 0, 2],
[2, 1, 1],
[0, 0, 2]
]
max_need = [
[7, 5, 3],
[3, 2, 2],
[9, 0, 2],
[2, 2, 2],
[4, 3, 3]
]
available = [3, 3, 2]
if flag == 0:
ans[ind] = i
ind += 1
for y in range(m):
available[y] += allocation[i][y]
f[i] = 1
print("\nExplaining the Safe Sequence:")
print("The safe sequence of processes ensures that the system can
avoid deadlock and complete execution.")
print("Safe sequence (processes in order):", [f"P{p}" for p in
ans])
Output:
Program to simulate MVT and MFT memory
management techniques
MVT:
class MVTMemory:
def __init__(self, total_memory):
self.total_memory = total_memory
self.memory_map = [(0, total_memory)] # Initial memory map
with one free block spanning the entire memory
mvt_memory.print_memory_map()
mvt_memory.deallocate_memory(200)
mvt_memory.deallocate_memory(400)
mvt_memory.print_memory_map()
OUTPUT:
MFT:
class MFTMemory:
def __init__(self, total_memory, block_size):
self.total_memory = total_memory
self.block_size = block_size
self.num_blocks = total_memory // block_size
self.memory_map = [(i * block_size, (i + 1) * block_size,
None) for i in range(self.num_blocks)]
def print_memory_map(self):
"""Print the current memory map."""
print("Memory Map:")
print("Start\tEnd\tProcess ID")
for start, end, pid in self.memory_map:
print(start, "\t", end, "\t", pid if pid is not None else
"Free")
mft_memory.print_memory_map()
mft_memory.deallocate_memory([0, 1, 2, 3, 4])
mft_memory.deallocate_memory([5, 6, 7])
mft_memory.print_memory_map()
Output:
Program to simulate page replacement algorithms
FIFO:
class FIFOPageReplacement:
def __init__(self, capacity):
self.capacity = capacity
self.pages = []
def display_pages(self):
"""Display pages currently in memory."""
print("Pages in memory:", self.pages)
pages = [1, 2, 3, 4, 1, 2]
for page in pages:
if fifo.page_fault(page):
print("Page", page, "caused a page fault")
else:
print("Page", page, "is already in memory")
fifo.display_pages()
OUTPUT:
LRU:
class LRUPageReplacement:
def __init__(self, capacity):
self.capacity = capacity
self.pages = []
def display_pages(self):
"""Display pages currently in memory."""
print("Pages in memory:", self.pages)
pages = [1, 2, 3, 4, 1, 2]
for page in pages:
if lru.page_fault(page):
print("Page", page, "caused a page fault")
else:
print("Page", page, "is already in memory")
lru.display_pages()
OUTPUT:
LFU:
from collections import defaultdict
class LFUPageReplacement:
def __init__(self, capacity):
self.capacity = capacity
self.pages = []
self.frequency = defaultdict(int)
def display_pages(self):
"""Display pages currently in memory."""
print("Pages in memory:", self.pages)
pages = [1, 2, 3, 4, 1, 2]
for page in pages:
if lfu.page_fault(page):
print("Page", page, "caused a page fault")
else:
print("Page", page, "is already in memory")
lfu.display_pages()
OUTPUT:
ROUND ROBIN:
def round_robin(processes, burst_time, quantum):
n = len(processes)
remaining_burst_time = burst_time[:]
time = 0
waiting_time = [0] * n
turnaround_time = [0] * n
timeline = [] # Timeline to store the sequence of processes
executed
while True:
done = True
for i in range(n):
if remaining_burst_time[i] > 0:
done = False
if remaining_burst_time[i] > quantum:
timeline.append(processes[i]) # Add process to
timeline
time += quantum
remaining_burst_time[i] -= quantum
else:
timeline.append(processes[i]) # Add process to
timeline
time += remaining_burst_time[i]
waiting_time[i] = time - burst_time[i]
remaining_burst_time[i] = 0
if done:
break
for i in range(n):
turnaround_time[i] = burst_time[i] + waiting_time[i]
# Example usage:
processes = [1, 2, 3, 4]
burst_time = [8, 6, 1, 9]
quantum = 2
OUTPUT:
Shortest Job First(SJF):
def sjf(processes, burst_time):
n = len(processes)
waiting_time = [0] * n
turnaround_time = [0] * n
timeline = [] # Timeline to store the sequence of processes
executed
# Example usage:
processes = [1, 2, 3, 4]
burst_time = [8, 6, 1, 9]
print("\nProcess Table:")
# Print table of processes, burst time, waiting time, and turnaround
time
OUTPUT:
First Come First Serve(FCFS):
def fcfs(processes, burst_time):
n = len(processes)
waiting_time = [0] * n
turnaround_time = [0] * n
timeline = [] # Timeline to store the sequence of processes
executed
# Example usage:
processes = [1, 2, 3, 4]
burst_time = [8, 6, 1, 9]
OUTPUT:
PRIORITY:
def priority_non_preemptive(processes, burst_time, priority):
n = len(processes)
waiting_time = [0] * n
turnaround_time = [0] * n
timeline = [] # Timeline to store the sequence of processes
executed
# Example usage:
processes = [1, 2, 3, 4]
burst_time = [8, 6, 1, 9]
priority = [3, 1, 2, 4]
OUTPUT:
1. Write a program to simulate all File Organization Techniques
a. Single level directory
class SingleLevelDirectory:
def __init__(self):
self.directory = {}
def list_files(self):
for file_type, files in self.directory.items():
print(f"{file_type}:")
for file_name in files:
print(f" - {file_name}")
Output:
b. Two Level
class TwoLevelDirectory:
def __init__(self):
self.directory = {}
def list_files(self):
for directory_name, files in self.directory.items():
print(f"{directory_name}:")
for file_name in files:
print(f" - {file_name}")
Output:
c. Tree-Structured Directories
class Directory:
def __init__(self, name):
self.name = name
self.subdirectories = {}
self.files = []
programs = root.add_subdirectory("Programs")
programs.add_file("calculator.exe")
programs.add_file("text_editor.exe")
Output:
d. Acyclic-Graph Directories
class File:
def __init__(self, name):
self.name = name
self.children = []
# Create files
file1 = File("File1")
file2 = File("File2")
file3 = File("File3")
file4 = File("File4")
file5 = File("File5")
# List contents
print("Contents of DAG Directory:")
file1.list_contents()
Output:
2. Write a program to simulate all file allocation strategies
a. Contiguous allocation
Dk
class ContiguousAllocation:
def __init__(self, total_blocks):
self.total_blocks = total_blocks
self.disk = [None] * total_blocks
def display_disk_status(self):
print("Disk Status:")
for i, block in enumerate(self.disk):
if block is None:
print(f"Block {i}: Free")
else:
print(f"Block {i}: Allocated to {block}")
# Allocate files
allocation.allocate_file("file1", 2, 3)
allocation.allocate_file("file2", 8, 4)
# Deallocate file1
allocation.deallocate_file("file1")
if file_name in self.index_table:
print(f"Error: File '{file_name}' already exists.")
return False
allocated_blocks = []
for i in range(num_blocks):
free_block = self._find_free_block()
if free_block is None:
print("Error: Not enough contiguous space on disk.")
self._deallocate_blocks(allocated_blocks)
return False
allocated_blocks.append(free_block)
self.disk[free_block] = file_name
self.index_table[file_name] = allocated_blocks
return True
allocated_blocks = self.index_table[file_name]
self._deallocate_blocks(allocated_blocks)
del self.index_table[file_name]
return True
def _find_free_block(self):
for i in range(self.total_blocks):
if self.disk[i] is None:
return i
return None
def display_disk_status(self):
print("Disk Status:")
for i, block in enumerate(self.disk):
if block is None:
print(f"Block {i}: Free")
else:
print(f"Block {i}: Allocated to {block}")
print("Index Table:")
for file_name, allocated_blocks in self.index_table.items():
print(f"{file_name}: {allocated_blocks}")
# Create an instance of IndexedAllocation with 10 blocks
allocation = IndexedAllocation(10)
# Allocate files
allocation.allocate_file("file1", 3)
allocation.allocate_file("file2", 2)
allocation.allocate_file("file3", 4)
# Deallocate file2
allocation.deallocate_file("file2")
class LinkedAllocation:
def __init__(self, total_blocks):
self.total_blocks = total_blocks
self.disk = [None] * total_blocks
self.free_blocks = set(range(total_blocks))
if file_name in self.disk:
print(f"Error: File '{file_name}' already exists.")
return False
head_block = None
prev_block = None
for i in range(num_blocks):
free_block = self.free_blocks.pop()
self.disk[free_block] = file_name
current_block = DiskBlock(free_block)
if prev_block:
prev_block.next_block = current_block
else:
head_block = current_block
prev_block = current_block
self.disk[file_name] = head_block
return True
head_block = self.disk[file_name]
current_block = head_block
while current_block:
self.free_blocks.add(current_block.block_number)
self.disk[current_block.block_number] = None
current_block = current_block.next_block
del self.disk[file_name]
return True
def display_disk_status(self):
print("Disk Status:")
for i, block in enumerate(self.disk):
if isinstance(block, DiskBlock):
print(f"Block {block.block_number}: Allocated to
{self.disk[block.block_number]}")
else:
print(f"Block {i}: Free")
# Create an instance of LinkedAllocation with 10 blocks
allocation = LinkedAllocation(10)
# Allocate files
allocation.allocate_file("file1", 3)
allocation.allocate_file("file2", 2)
allocation.allocate_file("file3", 4)
# Deallocate file2
allocation.deallocate_file("file2")
class PageTable:
def __init__(self, size):
self.size = size
self.table = {}
self.free_frames = list(range(size)) # Initialize free frames
def page_fault_handler(self, virtual_page):
if virtual_page in self.table:
# Page is already in memory, return corresponding frame
return self.table[virtual_page]
else:
# Page fault: Page is not in memory, allocate a frame
if len(self.free_frames) > 0:
frame = self.free_frames.pop(0) # Get a free frame
self.table[virtual_page] = frame # Map virtual page
to frame
return frame
else:
raise Exception("Out of memory: Cannot handle page
fault")
class MemoryManagementUnit:
def __init__(self, page_table):
self.page_table = page_table