0% found this document useful (0 votes)
9 views

Operating System With Python

operating system with python

Uploaded by

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

Operating System With Python

operating system with python

Uploaded by

Sandhiya Ammu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1.Basic I/O manipulation using CPU scheduling Algorithm.

def diamond(n):
for i in range(1, n + 1):
print(' ' * (n - i) + '*' * (2 * i - 1))
for i in range(n - 1, 0, -1):
print(' ' * (n - i) + '*' * (2 * i - 1))

diamond(5)
2. Shortest Job First Algorithm
print("Shortest Job First (Non-Preemptive) programming!".center(105, "~"), "\n")
# Processes
P = ['p1', 'p2', 'p3', 'p4']
p = P.copy()
# Arrival Times
AT = [0, 1, 2, 3]
at = AT.copy()
# Burst Times
BT = [8, 4, 9, 5]
bt = BT.copy()
GC = [] # Gantt chart
for i in range(len(P)):
miv = bt.index(min(bt)) # Find index of the minimum burst time
if i == 0:
miv = at.index(min(at)) # Find index of the minimum arrival time initially
GC.append([at[miv], p[miv], bt[miv]])
else:
GC.append([GC[i - 1][2], p[miv], GC[i - 1][2] + bt[miv]])

at.pop(miv)
p.pop(miv)
bt.pop(miv)

# Completion Time, Turn Around Time, Waiting Time


CT = [0] * len(P)
TAT = [0] * len(P)
WT = [0] * len(P)

for i in range(len(P)):
index = P.index(GC[i][1])
CT[index] = GC[i][2]
TAT[index] = CT[index] - AT[index]
WT[index] = TAT[index] - BT[index]

# Printing the results


print("*" * 105)
print("Process : Arrival Time : Burst Time : Completion Time : Turn Around Time : Waiting
Time")
for i in range(len(P)):
print(f"{P[i]}{' ' * 6} : {AT[i]}{' ' * 14} : {BT[i]}{' ' * 12} : {CT[i]}{' ' * 18} : {TAT[i]}{' ' *
18} : {WT[i]}")
print("*" * 105)

# Calculate averages
avg_TAT = sum(TAT) / len(P)
avg_WT = sum(WT) / len(P)
print(f"Average Turn Around Time: {avg_TAT}")
print(f"Average Waiting Time: {avg_WT}")
3. First Come First Served Algorithm.

print("FIRST COME FIRST SERVE SCHEDULING")


n = int(input("Enter number of processes : "))

d = {}

# Collecting process data


for i in range(n):
key = "P" + str(i + 1)
a = int(input("Enter arrival time of process " + str(i + 1) + ": "))
b = int(input("Enter burst time of process " + str(i + 1) + ": "))
l = [a, b]
d[key] = l

# Sorting processes by arrival time


d = sorted(d.items(), key=lambda item: item[1][0])

# Calculating Exit Time (ET), Turnaround Time (TAT), and Waiting Time (WT)
ET = []
TAT = []
WT = []
for i in range(len(d)):
if i == 0:
ET.append(d[i][1][0] + d[i][1][1]) # Exit time for first process
else:
ET.append(max(d[i][1][0], ET[i - 1]) + d[i][1][1])

TAT.append(ET[i] - d[i][1][0]) # Turnaround time


WT.append(TAT[i] - d[i][1][1]) # Waiting time

# Calculating average waiting time


avg_WT = sum(WT) / n

# Printing the results


print("Process | Arrival | Burst | Exit | Turn Around | Wait |")
for i in range(n):
print(f" {d[i][0]} | {d[i][1][0]} | {d[i][1][1]} | {ET[i]} | {TAT[i]} | {WT[i]} |")

print("Average Waiting Time: ", avg_WT)

4. Round Robin CPU Scheduling Algorithm.


def findWaitingTime(processes, n, bt, wt, quantum):
rem_bt = [0] * n

# Copy the burst time into rem_bt[]


for i in range(n):
rem_bt[i] = bt[i]
t = 0 # Current time

# Keep traversing processes in round robin manner until all are done
while True:
done = True

# Traverse all processes


for i in range(n):
if rem_bt[i] > 0:
done = False # There is a pending process

if rem_bt[i] > quantum:


t += quantum
rem_bt[i] -= quantum
else:
t += rem_bt[i]
wt[i] = t - bt[i]
rem_bt[i] = 0

# If all processes are done


if done:
break

def findTurnAroundTime(processes, n, bt, wt, tat):


# Calculating turnaround time
for i in range(n):
tat[i] = bt[i] + wt[i]

def findavgTime(processes, n, bt, quantum):


wt = [0] * n
tat = [0] * n

# Function to find waiting time of all processes


findWaitingTime(processes, n, bt, wt, quantum)

# Function to find turn around time for all processes


findTurnAroundTime(processes, n, bt, wt, tat)

# Display processes along with all details


print("Processes\tBurst Time\tWaiting Time\tTurn-Around Time")
total_wt = 0
total_tat = 0
for i in range(n):
total_wt += wt[i]
total_tat += tat[i]
print(f"{processes[i]}\t\t{bt[i]}\t\t{wt[i]}\t\t{tat[i]}")

print(f"\nAverage waiting time = {total_wt / n:.5f}")


print(f"Average turn around time = {total_tat / n:.5f}")
# Driver code
if __name__ == "__main__":
# Process IDs
processes = [1, 2, 3]
n = len(processes)

# Burst time of all processes


burst_time = [24, 3, 3]

# Time quantum
quantum = 4

findavgTime(processes, n, burst_time, quantum)

5.Priority Scheduling

def findWaitingTime(processes, n, wt):


wt[0] = 0
for i in range(1, n):
wt[i] = processes[i - 1][1] + wt[i - 1]

def findTurnAroundTime(processes, n, wt, tat):


for i in range(n):
tat[i] = processes[i][1] + wt[i]

def findavgTime(processes, n):


wt = [0] * n
tat = [0] * n

findWaitingTime(processes, n, wt)
findTurnAroundTime(processes, n, wt, tat)

print("\nProcesses\tBurst time\tWaiting Time\tTurn-Around Time")


total_wt = 0
total_tat = 0
for i in range(n):
total_wt += wt[i]
total_tat += tat[i]
print(f" {processes[i][0]}\t\t{processes[i][1]}\t\t{wt[i]}\t\t{tat[i]}")

print(f"\nAverage turn around time = {total_tat / n}")


print(f"Average Waiting time = {total_wt / n}")

def priorityScheduling(proc, n):


proc = sorted(proc, key=lambda proc: proc[2]) # Sort processes by priority (ascending)
print("Order in which processes get executed:")

for i in proc:
print(i[0], end=" ")
print() # Print newline for better formatting
findavgTime(proc, n)

if __name__ == "__main__":
# Process IDs, Burst time, and Priority
proc = [
[1, 10, 3],
[2, 1, 1],
[3, 2, 3],
[4, 1, 4],
[5, 5, 2]
]
n=5

priorityScheduling(proc, n)

6. To implement reader/writer problem using semaphore.


import threading
import time

class ReaderWriterProblem:
def __init__(self):
self.mutex = threading.Semaphore(1) # Semaphore for mutual exclusion
self.wrt = threading.Semaphore(1) # Semaphore for controlling write access
self.r_c = 0 # Number of current readers

def reader(self):
while True:
self.mutex.acquire()
self.r_c += 1

if self.r_c == 1:
self.wrt.acquire() # First reader acquires write lock

self.mutex.release()

print(f"\nReader {self.r_c} is reading")

self.mutex.acquire()
self.r_c -= 1

if self.r_c == 0:
self.wrt.release() # Last reader releases write lock

self.mutex.release()

time.sleep(3)
def writer(self):
while True:
self.wrt.acquire()
print("Writing data .......")
print("-" * 20)
self.wrt.release()
time.sleep(3)

def main(self):
t1 = threading.Thread(target=self.reader)
t2 = threading.Thread(target=self.writer)
t3 = threading.Thread(target=self.reader)
t4 = threading.Thread(target=self.reader)
t5 = threading.Thread(target=self.reader)
t6 = threading.Thread(target=self.writer)

t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
t6.start()

if __name__ == "__main__":
rw = ReaderWriterProblem()
rw.main()
7. To implement Banker’s algorithm for Deadlock avoidance.
Program for page replacement algorithms:

P = 5 # Number of processes
R = 3 # Number of resources

def calculateNeed(need, maxm, allot):


"""
Function to calculate the Need matrix.
need[i][j] = maxm[i][j] - allot[i][j]
"""
for i in range(P):
for j in range(R):
need[i][j] = maxm[i][j] - allot[i][j]

def isSafe(processes, avail, maxm, allot):


"""
Function to check if the system is in a safe state using Banker's Algorithm.
"""
need = [[0] * R for _ in range(P)]
calculateNeed(need, maxm, allot)

finish = [0] * P
safeSeq = []
work = avail[:]

count = 0
while count < P:
found = False
for p in range(P):
if finish[p] == 0:
# Check if the current process can be executed
for j in range(R):
if need[p][j] > work[j]:
break
else:
# If all resources for current process can be allocated
for k in range(R):
work[k] += allot[p][k]

safeSeq.append(p)
finish[p] = 1
found = True
count += 1

if not found:
print("System is not in a safe state")
return False

print("System is in a safe state.\nSafe sequence is: ", safeSeq)


return True

if __name__ == "__main__":
processes = [0, 1, 2, 3, 4]

avail = [3, 3, 2]

maxm = [
[7, 5, 3],
[3, 2, 2],
[9, 0, 2],
[2, 2, 2],
[4, 3, 3]
]

allot = [
[0, 1, 0],
[2, 0, 0],
[3, 0, 2],
[2, 1, 1],
[0, 0, 2]
]

isSafe(processes, avail, maxm, allot)

8. First In First Out Algorithm.


from queue import Queue

def pageFaults(pages, n, capacity):


s = set()
indexes = Queue()
page_faults = 0

for i in range(n):
if len(s) < capacity:
if pages[i] not in s:
s.add(pages[i])
page_faults += 1
indexes.put(pages[i])
else:
if pages[i] not in s:
val = indexes.queue[0]
indexes.get()
s.remove(val)
s.add(pages[i])
indexes.put(pages[i])
page_faults += 1

print(s, end=" ")


print("Page Fault Count", page_faults)

return page_faults

if __name__ == "__main__":
pages = [3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4]
n = len(pages)
capacity = 3
print("Total page fault count:", pageFaults(pages, n, capacity))
9. Least Recently Used Algorithm.
# Python3 program for LRU page replacement algorithm

def LRU(page_size, reference_string):


# Creating a list to store the current pages in memory
pages = []

# Page faults and hits counters


faults = 0
hits = 0

# Iterating through the reference string


for ref_page in reference_string:
# If ref_page already exists in pages list, remove it and append it at the end
if ref_page in pages:
pages.remove(ref_page)
pages.append(ref_page)
hits += 1 # Increment page hits

# If ref_page is not in the pages list


else:
faults += 1 # Increment page faults

# Check length of the pages list. If less than page size, append ref_page
if len(pages) < page_size:
pages.append(ref_page)
else:
# If full, remove the least recently used page (first element) and append ref_page
pages.pop(0)
pages.append(ref_page)

# Printing the number of page hits and page faults


print("Total number of Page Hits:", hits)
print("Total number of Page Faults:", faults)

if __name__ == "__main__":
# Given page size and reference string
page_size = 3
reference_string = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 1, 2, 0]

# Calling the LRU function with given parameters


LRU(page_size, reference_string)

10. To implement first fit, best fit and worst fit algorithm for memory management.
def FirstFit(block_size, blocks, process_size, processes):
allocate = [-1] * processes
occupied = [False] * blocks
for i in range(processes):
for j in range(blocks):
if not occupied[j] and (block_size[j] >= process_size[i]):
allocate[i] = j
occupied[j] = True
break

print("Process No.\tProcess Size\tBlock No.")


for i in range(processes):
print(i + 1, "\t\t", process_size[i], "\t\t", end=" ")
if allocate[i] != -1:
print(allocate[i] + 1)
else:
print("Not Allocated")

block_size = [20, 100, 40, 200, 10]


process_size = [90, 50, 30, 40]
m = len(block_size)
n = len(process_size)

FirstFit(block_size, m, process_size, n)

11. Write a Python program to simulate the Best- Fit

def bestFit(blockSize, m, processSize, n):


# Stores block id of the block allocated to a process
allocation = [-1] * n

# Pick each process and find suitable blocks according to its size and assign to it
for i in range(n):
# Find the best fit block for current process
bestIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if bestIdx == -1 or blockSize[bestIdx] > blockSize[j]:
bestIdx = j

# If we could find a block for current process


if bestIdx != -1:
# Allocate block j to p[i] process
allocation[i] = bestIdx
# Reduce available memory in this block.
blockSize[bestIdx] -= processSize[i]

print("Process No.\tProcess Size\tBlock no.")


for i in range(n):
print(i + 1, "\t\t", processSize[i], "\t\t", end=" ")
if allocation[i] != -1:
print(allocation[i] + 1)
else:
print("Not Allocated")
# Driver code
if __name__ == '__main__':
blockSize = [100, 500, 200, 300, 600]
processSize = [212, 417, 112, 426]
m = len(blockSize)
n = len(processSize)

bestFit(blockSize, m, processSize, n)

12. implement worst fit algorithm for memory management


def worstFit(blockSize, m, processSize, n):
# Stores block id of the block allocated to a process
allocation = [-1] * n

# Pick each process and find suitable blocks according to its size and assign to it
for i in range(n):
# Find the worst fit block for the current process
wstIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if wstIdx == -1 or blockSize[wstIdx] < blockSize[j]:
wstIdx = j

# If we could find a block for the current process


if wstIdx != -1:
# Allocate block j to p[i] process
allocation[i] = wstIdx
# Reduce available memory in this block.
blockSize[wstIdx] -= processSize[i]

print("Process No.\tProcess Size\tBlock no.")


for i in range(n):
print(i + 1, "\t\t", processSize[i], "\t\t", end=" ")
if allocation[i] != -1:
print(allocation[i] + 1)
else:
print("Not Allocated")

# Driver code
if __name__ == '__main__':
blockSize = [100, 500, 200, 300, 600]
processSize = [212, 417, 112, 426]
m = len(blockSize)
n = len(processSize)

worstFit(blockSize, m, processSize, n)

13. Program for Inter-process Communication.


import multiprocessing

def sender(conn, msgs):


"""
Function to send messages to the other end of the pipe
"""
for msg in msgs:
conn.send(msg)
print("Sent the message: {}".format(msg))
conn.close()

def receiver(conn):
"""
Function to print the messages received from the other
end of the pipe
"""
while True:
msg = conn.recv()
if msg == "END":
break
print("Received the message: {}".format(msg))

if __name__ == "__main__":
# Messages to be sent
msgs = ["hello", "hey", "hru?", "END"]

# Creating a pipe
parent_conn, child_conn = multiprocessing.Pipe()

# Creating new processes


p1 = multiprocessing.Process(target=sender, args=(parent_conn, msgs))
p2 = multiprocessing.Process(target=receiver, args=(child_conn,))

# Running processes
p1.start()
p2.start()

# Wait until processes finish


p1.join()
p2.join()

You might also like