0% found this document useful (0 votes)
25 views19 pages

Os Codes

The document contains code implementations for various CPU scheduling and memory management algorithms, including FCFS, SJF, Round Robin, Banker's algorithm, FIFO, OPT, LRU, and disk scheduling methods like SCAN and SSTF. Each section provides a function to calculate waiting times, turnaround times, or page faults, along with user input prompts for process or memory details. The algorithms are designed to demonstrate different strategies for resource allocation and process scheduling in operating systems.

Uploaded by

crce.9915.ce
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)
25 views19 pages

Os Codes

The document contains code implementations for various CPU scheduling and memory management algorithms, including FCFS, SJF, Round Robin, Banker's algorithm, FIFO, OPT, LRU, and disk scheduling methods like SCAN and SSTF. Each section provides a function to calculate waiting times, turnaround times, or page faults, along with user input prompts for process or memory details. The algorithms are designed to demonstrate different strategies for resource allocation and process scheduling in operating systems.

Uploaded by

crce.9915.ce
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/ 19

1.

FCFS(CPU)
CODE
def calculate_waiting_time(n, bt, wt):
wt[0] = 0
for i in range(1, n):
wt[i] = bt[i - 1] + wt[i - 1]

def calculate_turnaround_time(n, bt, wt, tat):


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

def find_average_time(n, bt):


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

calculate_waiting_time(n, bt, wt)


calculate_turnaround_time(n, bt, wt, tat)

print("Processes Burst Time Waiting Time Turnaround Time")


for i in range(n):
total_wt += wt[i]
total_tat += tat[i]
print(" ", i + 1, "\t\t", bt[i], "\t\t", wt[i], "\t\t", tat[i])

print("\nAverage waiting time =", round(total_wt / n, 2))


print("Average turnaround time =", round(total_tat / n, 2))

if __name__ == "__main__":
n = int(input("Enter the number of processes: "))
burst_time = []

print("Enter burst time for each process:")


for i in range(n):
bt = int(input(f"Enter burst time for process {i+1}: "))
burst_time.append(bt)

find_average_time(n, burst_time)
2. SJF
CODE
# Initialize waiting time and turnaround time arrays
waiting_time = [0] * n
turnaround_time = [0] * n

# Calculate waiting time and turnaround time


for i in range(1, n):
waiting_time[i] = sum(burst_time[:i]) - arrival_time[i]
turnaround_time[i] = waiting_time[i] + burst_time[i]

# Calculate average waiting time and average turnaround time


avg_waiting_time = sum(waiting_time) / n
avg_turnaround_time = sum(turnaround_time) / n

# Print the table


print("Process\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time")
for i in range(n):

print(f"{processes[i][0]}\t{processes[i][1]}\t\t{processes[i][2]}\t\t{waiting_time[i]}\t\t{turnaround_tim
e[i]}")

# Print the calculated averages


print("\nAverage Waiting Time:", avg_waiting_time)
print("Average Turnaround Time:", avg_turnaround_time)

def main():
# Taking user input for number of processes
n = int(input("Enter the number of processes: "))

processes = []
for i in range(n):
process_id = input(f"Enter Process ID for process {i + 1}: ")
burst_time = int(input(f"Enter Burst Time for process {i + 1}: "))
arrival_time = int(input(f"Enter Arrival Time for process {i + 1}: "))
processes.append((process_id, burst_time, arrival_time))

sjf_scheduling(processes)

if __name__ == "__main__":
main()
3. ROUND
CODE

def round_robin_scheduling(processes, quantum):


n = len(processes)
remaining_burst_time = [process[1] for process in processes]
waiting_time = [0] * n
turnaround_time = [0] * n
total_time = 0
time_quantum = quantum

while True:
done = True
for i in range(n):
if remaining_burst_time[i] > 0:
done = False
if remaining_burst_time[i] > time_quantum:
total_time += time_quantum
remaining_burst_time[i] -= time_quantum
else:
total_time += remaining_burst_time[i]
waiting_time[i] = total_time - processes[i][1]
remaining_burst_time[i] = 0

if done:
break

for i in range(n):
turnaround_time[i] = waiting_time[i] + processes[i][1]

avg_waiting_time = sum(waiting_time) / n
avg_turnaround_time = sum(turnaround_time) / n

# Print the table


print("Process\tBurst Time\tWaiting Time\tTurnaround Time")
for i in range(n):
print(f"{processes[i][0]}\t{processes[i][1]}\t\t{waiting_time[i]}\t\t{turnaround_time[i]}")

# Print the calculated averages


print("\nAverage Waiting Time:", avg_waiting_time)
print("Average Turnaround Time:", avg_turnaround_time)

def main():
# Taking user input for number of processes
n = int(input("Enter the number of processes: "))

processes = []
for i in range(n):
process_id = input(f"Enter Process ID for process {i + 1}: ")
burst_time = int(input(f"Enter Burst Time for process {i + 1}: "))
processes.append((process_id, burst_time))

quantum = int(input("Enter the time quantum: "))

round_robin_scheduling(processes, quantum)

if __name__ == "__main__":
main()
4. BANKER
ccode

def bankers_algorithm(alloc, max_resources, avail_resources):


n = len(alloc)
m = len(alloc[0])
need = [[max_resources[i][j] - alloc[i][j] for j in range(m)] for i in range(n)]
finish = [False] * n
safe_sequence = []
work = avail_resources[:]

while True:
found = False
for i in range(n):
if not finish[i] and all(need[i][j] <= work[j] for j in range(m)):
safe_sequence.append(i)
finish[i] = True
work = [work[j] + alloc[i][j] for j in range(m)]
found = True
break

if not found:
break

return safe_sequence if all(finish) else None

def main():
num_processes = int(input("Enter the number of processes: "))
num_resources = int(input("Enter the number of resources: "))

print("Enter allocation matrix:")


allocation = [list(map(int, input().split())) for _ in range(num_processes)]

print("Enter maximum resources matrix:")


max_resources = [list(map(int, input().split())) for _ in range(num_processes)]

print("Enter available resources:")


available_resources = list(map(int, input().split()))

safe_sequence = bankers_algorithm(allocation, max_resources, available_resources)

print("\nNeed Matrix:")
for i in range(num_processes):
need = [max_resources[i][j] - allocation[i][j] for j in range(num_resources)]
print(" ".join(map(str, need)))

if safe_sequence:
print("\nSafe sequence:", safe_sequence)
else:
print("\nNo safe sequence exists!")

if __name__ == "__main__":
main()
5. FIFO
ccode

def fifo_page_replacement(frames, page_sequence):


page_faults = 0
frame_queue = []

for page in page_sequence:


if page not in frame_queue:
if len(frame_queue) < frames:
frame_queue.append(page)
else:
frame_queue.pop(0)
frame_queue.append(page)
page_faults += 1

return page_faults

def main():
# Taking user input for number of frames
num_frames = int(input("Enter the number of frames: "))

# Taking user input for page reference sequence


page_sequence = list(map(int, input("Enter the page reference sequence separated by
spaces: ").split()))

# Calculate page faults using FIFO page replacement algorithm


page_faults = fifo_page_replacement(num_frames, page_sequence)

# Display the output


print("Page Faults:", page_faults)

if __name__ == "__main__":
main()
6. OPT
ccode

def opt_page_replacement(frames, page_sequence):


page_faults = 0
frame_set = set()
frame_list = []

for page in page_sequence:


if page not in frame_set:
if len(frame_set) < frames:
frame_set.add(page)
else:
page_faults += 1
idx = -1
farthest = -1
for i, frame in enumerate(frame_list):
if frame not in page_sequence:
idx = i
break
elif page_sequence.index(frame) > farthest:
farthest = page_sequence.index(frame)
idx = i
frame_set.remove(frame_list[idx])
frame_list.pop(idx)
frame_set.add(page)
frame_list.append(page)

return page_faults

def main():
# Taking user input for number of frames
num_frames = int(input("Enter the number of frames: "))

# Taking user input for page reference sequence


page_sequence = list(map(int, input("Enter the page reference sequence separated by
spaces: ").split()))

# Calculate page faults using OPT page replacement algorithm


page_faults = opt_page_replacement(num_frames, page_sequence)

# Display the output


print("Page Faults:", page_faults)
if __name__ == "__main__":
main()
7. LRU
Code

def lru_page_replacement(frames, page_sequence):


page_faults = 0
frame_list = []

for page in page_sequence:


if page not in frame_list:
if len(frame_list) < frames:
frame_list.append(page)
else:
frame_list.pop(0)
frame_list.append(page)
page_faults += 1
else:
frame_list.remove(page)
frame_list.append(page)

return page_faults

def main():
# Taking user input for number of frames
num_frames = int(input("Enter the number of frames: "))

# Taking user input for page reference sequence


page_sequence = list(map(int, input("Enter the page reference sequence separated by
spaces: ").split()))

# Calculate page faults using LRU page replacement algorithm


page_faults = lru_page_replacement(num_frames, page_sequence)

# Display the output


print("Page Faults:", page_faults)

if __name__ == "__main__":
main()
8. FCFS(I/O)
Code

def fcfs_disk_scheduling(initial_position, requests):


total_movement = 0
current_position = initial_position

# Calculate total movement


for request in requests:
total_movement += abs(request - current_position)
current_position = request

return total_movement

def main():
# Taking user input for initial position of disk head
initial_position = int(input("Enter the initial position of the disk head: "))

# Taking user input for sequence of disk requests


request_sequence = input("Enter the sequence of disk requests separated by spaces:
").split()
request_sequence = list(map(int, request_sequence))

# Perform FCFS disk scheduling


total_movement = fcfs_disk_scheduling(initial_position, request_sequence)

# Calculate average seek time


average_seek_time = total_movement / len(request_sequence)

# Display total head movement and average seek time


print("Total head movement:", total_movement)
print("Average seek time:", average_seek_time)

if __name__ == "__main__":
main()
9. SSCAN
code

def scan_disk_scheduling(initial_position, requests, direction, total_tracks):


total_movement = 0
current_position = initial_position
sequence = []

while True:
if direction == "left":
nearest_request = max([req for req in requests if req <= current_position] + [0])
if nearest_request == 0:
total_movement += current_position
current_position = 0
direction = "right"
else:
total_movement += abs(nearest_request - current_position)
current_position = nearest_request
sequence.append(current_position)
requests.remove(current_position)
elif direction == "right":
nearest_request = min([req for req in requests if req >= current_position] + [total_tracks])
if nearest_request == total_tracks:
total_movement += total_tracks - current_position
current_position = total_tracks
direction = "left"
else:
total_movement += abs(nearest_request - current_position)
current_position = nearest_request
sequence.append(current_position)
requests.remove(current_position)

if not requests:
break

return total_movement, sequence

def main():
# Taking user input for initial position of disk head
initial_position = int(input("Enter the initial position of the disk head: "))

# Taking user input for sequence of disk requests


request_sequence = list(map(int, input("Enter the sequence of disk requests separated by
spaces: ").split()))

# Taking user input for the direction of movement


direction = input("Enter the direction of movement (left/right): ").lower()

# Taking user input for total number of tracks


total_tracks = int(input("Enter the total number of tracks: "))

# Perform SCAN disk scheduling


total_movement, sequence = scan_disk_scheduling(initial_position, request_sequence,
direction, total_tracks)

# Calculate average seek time


average_seek_time = total_movement / len(sequence)

# Display total head movement, sequence, and average seek time


print("Total head movement:", total_movement)
print("Sequence of disk requests:", sequence)
print("Average seek time:", average_seek_time)

if __name__ == "__main__":
main()
10. SSIF
Code

def sstf_disk_scheduling(initial_position, requests):


total_movement = 0
current_position = initial_position
sequence = []

while requests:
nearest_request = min(requests, key=lambda x: abs(x - current_position))
total_movement += abs(nearest_request - current_position)
current_position = nearest_request
sequence.append(current_position)
requests.remove(current_position)

return total_movement, sequence

def main():
# Taking user input for initial position of disk head
initial_position = int(input("Enter the initial position of the disk head: "))

# Taking user input for sequence of disk requests


request_sequence = list(map(int, input("Enter the sequence of disk requests separated by
spaces: ").split()))

# Perform SSTF disk scheduling


total_movement, sequence = sstf_disk_scheduling(initial_position, request_sequence)

# Calculate average seek time


average_seek_time = total_movement / len(sequence)

# Display total head movement, sequence, and average seek time


print("Total head movement:", total_movement)
print("Sequence of disk requests:", sequence)
print("Average seek time:", average_seek_time)

if __name__ == "__main__":
main()
11. FIRST
Code

def first_fit(memory_blocks, process_sizes):


allocation = [-1] * len(process_sizes)

for i in range(len(process_sizes)):
for j in range(len(memory_blocks)):
if memory_blocks[j] >= process_sizes[i]:
allocation[i] = j
memory_blocks[j] -= process_sizes[i]
break

return allocation

def main():
# Taking user input for the number of memory blocks and their sizes
num_blocks = int(input("Enter the number of memory blocks: "))
memory_sizes = list(map(int, input("Enter the sizes of memory blocks separated by spaces:
").split()))

# Taking user input for the number of processes and their sizes
num_processes = int(input("Enter the number of processes: "))
process_sizes = list(map(int, input("Enter the sizes of processes separated by spaces:
").split()))

# Perform First Fit memory allocation


allocation = first_fit(memory_sizes, process_sizes)

# Display allocation table


print("\nAllocation Table:")
print("Process No.\tProcess Size\tBlock No.")
for i in range(len(process_sizes)):
if allocation[i] != -1:
print(f"{i}\t\t\t{process_sizes[i]}\t\t\t{allocation[i]}")
else:
print(f"{i}\t\t\t{process_sizes[i]}\t\t\tNot Allocated")

if __name__ == "__main__":
main()
12. BEST
Code

def best_fit(memory_blocks, process_sizes):


allocation = [-1] * len(process_sizes)

for i in range(len(process_sizes)):
best_idx = -1
for j in range(len(memory_blocks)):
if memory_blocks[j] >= process_sizes[i]:
if best_idx == -1 or memory_blocks[j] < memory_blocks[best_idx]:
best_idx = j

if best_idx != -1:
allocation[i] = best_idx
memory_blocks[best_idx] -= process_sizes[i]

return allocation

def main():
# Taking user input for the number of memory blocks and their sizes
num_blocks = int(input("Enter the number of memory blocks: "))
memory_sizes = list(map(int, input("Enter the sizes of memory blocks separated by spaces:
").split()))

# Taking user input for the number of processes and their sizes
num_processes = int(input("Enter the number of processes: "))
process_sizes = list(map(int, input("Enter the sizes of processes separated by spaces:
").split()))

# Perform Best Fit memory allocation


allocation = best_fit(memory_sizes, process_sizes)

# Display allocation table


print("\nAllocation Table:")
print("Process No.\tProcess Size\tBlock No.")
for i in range(len(process_sizes)):
if allocation[i] != -1:
print(f"{i}\t\t\t{process_sizes[i]}\t\t\t{allocation[i]}")
else:
print(f"{i}\t\t\t{process_sizes[i]}\t\t\tNot Allocated")

if __name__ == "__main__":
main()
13. WORST
Code

def worst_fit(memory_blocks, process_sizes):


allocation = [-1] * len(process_sizes)

for i in range(len(process_sizes)):
worst_idx = -1
for j in range(len(memory_blocks)):
if memory_blocks[j] >= process_sizes[i]:
if worst_idx == -1 or memory_blocks[j] > memory_blocks[worst_idx]:
worst_idx = j

if worst_idx != -1:
allocation[i] = worst_idx
memory_blocks[worst_idx] -= process_sizes[i]

return allocation

def main():
# Taking user input for the number of memory blocks and their sizes
num_blocks = int(input("Enter the number of memory blocks: "))
memory_sizes = list(map(int, input("Enter the sizes of memory blocks separated by spaces:
").split()))

# Taking user input for the number of processes and their sizes
num_processes = int(input("Enter the number of processes: "))
process_sizes = list(map(int, input("Enter the sizes of processes separated by spaces:
").split()))

# Perform Worst Fit memory allocation


allocation = worst_fit(memory_sizes, process_sizes)

# Display allocation table


print("\nAllocation Table:")
print("Process No.\tProcess Size\tBlock No.")
for i in range(len(process_sizes)):
if allocation[i] != -1:
print(f"{i}\t\t\t{process_sizes[i]}\t\t\t{allocation[i]}")
else:
print(f"{i}\t\t\t{process_sizes[i]}\t\t\tNot Allocated")
if __name__ == "__main__":
main()

You might also like