os_lab_sheets
os_lab_sheets
OPERATING SYSTEM
CSE3003
LAB FILE
Submitted to Submitted by
Dr. Santosh Kumar Sahoo Dhruv Jadhav
22BCE11444 Dhruv Jadhav
CONTENT
Observation:
Process Management:
File Management:
22BCE11444 Dhruv Jadhav
for p in processes:
p['remaining'] =
p['burst'] p['start'] =
None p['completed'] =
False
time = 0
completed_count = 0
order = []
total_wt = total_tat = 0
foreground =
Queue() background
= Queue()
time_quantum = 2
time = 0
for p in processes:
p['remaining'] =
p['burst'] p['waiting'] =
0
p['turnaround'] = 0
p['started'] = False
completed = []
total_wt = total_tat = 0
if not
foreground.empty():
proc =
foreground.get() if
not proc['started']:
proc['start_time'] = time
proc['started'] = True
run_time = min(time_quantum, proc['remaining'])
proc['remaining'] -=
run_time if
proc['remaining'] > 0:
foreground.put(proc
) else:
proc['turnaround'] = time - proc['arrival']
proc['waiting'] = proc['turnaround'] -
proc['burst'] total_wt += proc['waiting']
total_tat += proc['turnaround']
completed.append(proc)
elif not
background.empty():
proc =
background.get() if
not proc['started']:
proc['start_time'] = time
proc['started'] = True
proc['remaining'] = 0
proc['turnaround'] = time - proc['arrival']
proc['waiting'] = proc['turnaround'] - proc['burst']
total_wt += proc['waiting']
total_tat += proc['turnaround']
completed.append(proc)
22BCE11444 Dhruv Jadhav
Observation:
(a) Contiguous Allocation using Array
class Block:
def init (self, index):
self.index = index
self.next = None
def linked_allocation(free_blocks,
file_size): if len(free_blocks) <
file_size:
return None
blocks = random.sample(free_blocks,
file_size) head = Block(blocks[0])
current = head
for i in range(1, file_size):
current.next = Block(blocks[i])
22BCE11444 Dhruv Jadhav
current = current.next
return head
600]
processes = [212, 417, 112, 426]
22BCE11444 Dhruv Jadhav
def allocate(strategy):
blocks = memory_blocks.copy()
allocation = [-1] * len(files)
internal_frag = [0] *
len(files)
if strategy == 'first_fit':
for i, fsize in
enumerate(files): for j in
range(len(blocks)):
if blocks[j] >=
fsize:
allocation[i] =
j
internal_frag[i] = blocks[j] -
fsize blocks[j] = -1 # Mark
block as used break
worst_index
internal_frag[i] = blocks[worst_index] -
fsize blocks[worst_index] = -1
22BCE11444 Dhruv Jadhav
# Internal Fragmentation
total_internal = sum(internal_frag)
for s in strategies:
alloc, internal, external = allocate(s)
results[s] = {
'allocation': alloc,
'internal_fragmentation': internal,
'external_fragmentation': external
}
# Print Results
"
print("\nObservation Table: Fragmentation )
print("Strategy | Internal Frag (KB) | External Frag
(KB)")
print(" ")
for strategy in strategies:
sname = strategy.replace('_', ' ').title().ljust(14)
i_frag = results[strategy]['internal_fragmentation']
e_frag = results[strategy]['external_fragmentation']
print(f"{sname} | {str(i_frag).ljust(20)} |
{e_frag}")
22BCE11444 Dhruv Jadhav
for f in files:
for block in memory:
if not block['allocated'] and block['size'] >= f:
block['allocated'] = True
block['file'] = f
internal_frag += block['size']
- f break
# Compaction Logic
def perform_compaction(memory):
# Move all allocated blocks to the
beginning compacted_memory = []
total_movement = 0
# Accumulate allocated
blocks for block in memory:
if block['allocated']:
compacted_memory.append({'size': block['file'], 'allocated':
True, 'file': block['file']})
total_movement += block['file'] # Simulate moving file data
# Run allocation
memory, internal_before = first_fit_allocation(initial_blocks, files)
22BCE11444 Dhruv Jadhav
# Perform compaction
compacted_memory, data_movement = perform_compaction(memory)
# Final Observation
internal_after = 0 # Internal fragmentation removed
external_after = sum(block['size'] for block in compacted_memory
if not block['allocated'])
# Observation Table
print("\nObservation Table: Compaction
Analysis") print(" "
print("Fragmentation Type )
| Before Compaction | After Compaction")
print(" ")
print(f"Internal | {internal_before:<20} |
Fragmentation {internal_after}")
| 0 | {external_after}")
print(f"External | | {data_movement}
Fragmentation print(f"Total N/A KB")
")
22BCE11444 Dhruv Jadhav
Observation:
Case 1: Single Instance of Resources
the Resource Allocation Graph (RAG) for Case 1 where each resource has only one
instance:
Here's the Resource Allocation Graph (RAG) for the case where multiple instances of
resources exist.
Resources (R1, R2) are shown as squares with instance numbers (e.g.,
R1_1, R1_2).
class ResourceAllocationGraph:
def init (self, processes, resources, instances=None):
self.processes = processes
self.resources = resources
self.instances = instances if instances else {r: 1 for r in resources}
self.graph = {}
# Initialize nodes
for p in
processes:
self.graph[p] = []
for r in resources:
for i in range(self.instances[r]):
self.graph[f"{r}_{i+1}"] = []
def display_graph(self):
print("\n--- Resource Allocation Graph (Adjacency List)
---") for node in self.graph:
print(f"{node} --> {self.graph[node]}")
#
# G Example usage (Case 2: Multiple
instances) processes = ['P1', 'P2', 'P3']
resources = ['R1', 'R2']
instances = {'R1': 2, 'R2': 2}
rag.display_graph()
22BCE11444 Dhruv Jadhav
Banker’s Algorithm
need = []
for i in
range(len(maximum)):
row = []
for j in range(len(maximum[0])):
row.append(maximum[i][j] - allocation[i]
[j])
need.append(row)
return need
finish = [False] *
n safe_sequence =
[] work =
available[:]
print("\nNeed
Matrix:") for i in
range(n):
print(f"P{i}:", need[i])
is_safe = len(safe_sequence) ==
n return is_safe, safe_sequence
# Sample input
processes = ["P0", "P1", "P2", "P3", "P4"]
22BCE11444 Dhruv Jadhav
available = [3, 3, 2]
22BCE11444 Dhruv Jadhav
maximum = [
[7, 5,
3],
[3, 2,
2],
[9, 0,
2],
[2, 2,
2],
[4, 3, 3]
[0, 1, 0],
[2, 0, 0],
[3, 0, 2],
[2, 1, 1],
[0, 0, 2]
]
# Output
print("\nBanker’s Algorithm
Result:") if safe:
print("✅ The system is in a SAFE state.")
print("Safe sequence:", " → ".join(sequence))
else:
print("❌ The system is in an UNSAFE state. Deadlock may
22BCE11444 Dhruv Jadhav
Implementation:
import networkx as nx
import matplotlib.pyplot as plt
for u, v in rag.edges():
if u.startswith('P') and
v.startswith('R'): for successor in
rag.successors(v):
if successor.startswith('P'):
wfg.add_edge(u, successor)
Observation:
22BCE11444 Dhruv Jadhav
Implementation:
import java.util.concurrent.*;
}
}
Implementation:
import java.util.concurrent.*;
System.out.println("Reader is reading");
Thread.sleep(1000);
mutex.acquire(
);
readCount--;
if (readCount == 0)
wrt.release();
mutex.release();
} catch (Exception e) {}
}
}
new
Writer().start();
new
Reader().start();
}
Implementation:
import java.util.concurrent.*;
Philosopher(int id) {
this.id = id;
}
forks[id].release();
22BCE11444 Dhruv Jadhav
forks[(id + 1) % 5].release();
}
} catch (Exception e) {}
}
}
Implementation:
public class AadharAverage {
child.start(); // Fork
child.join(); // Join (Child finishes before Parent)
parent.start();
}
}
22BCE11444 Dhruv Jadhav
Implementation:
public class PrimeFORKJOIN {
static int[] primeArray = {2, 3, 5, 7, 11, 13, 17, 31, 37, 113, 197, 199};
child.start(); // FORK
try {
child.join(); // JOIN
} catch (InterruptedException e) {
e.printStackTrace();
}