Professional Documents
Culture Documents
9882 OS Ex6
9882 OS Ex6
9882 OS Ex6
Problem Statements:
WAP for the following.
Inputs: Number of processes, No of Resources, Instances of each resources, Number of resources
held by each process, Number of resources needed by each process/Maximum number of resources
needed by each process.
Write a menu driven program.
1) Detect if a deadlock exists. Also show the processes involved in deadlock
2) Check if the deadlock can be avoided (using bankers algo.). If yes, give the safe state sequence.
Code:
def is_safe(processes, available, max_need, allocated):
n = len(processes)
m = len(available)
# Initialize work and finish arrays
work = available.copy() finish =
[False] * n safe_sequence = []
# Copy the allocated matrix to the need matrix
need = [] for i in range(n):
need.append([0] * m)
for j in range(m):
need[i][j] = max_need[i][j] - allocated[i][j]
# Loop until all processes are finished or deadlock is detected
while True:
found = False
for i in range(n): if not
finish[i] and all(need[i]
Fr. CRCE Operating Systems Lab 2023-2024
def main():
while True:
print("\nMenu:") print("1.
Detect if a deadlock exists")
print("2. Check if the deadlock can be avoided (using Banker's algorithm)")
print("3. Exit") choice = input("Enter your choice: ")
if choice ==
'1':
deadlock, processes_involved = detect_deadlock(processes,
available_resources, max_need, allocated) if deadlock:
print("Deadlock detected!") print("Processes
involved in deadlock:", processes_involved) else:
print("No deadlock detected.")
else:
print("Invalid choice. Please enter a valid option.")
if __name__ == "__main__":
n = int(input("Enter the number of processes: "))
m = int(input("Enter the number of resources: "))
processes = [] for i in range(n):
processes.append(input(f"Enter the name of process {i + 1}: "))
available_resources = [] print("Enter the number of instances of
each resource:") for i in range(m):
available_resources.append(int(input(f"Resource {i + 1}: ")))
allocated = []
print("Enter the number of resources allocated to each process:")
for i in range(n):
allocated.append(list(map(int, input(f"For process {processes[i]}:
").split())))
if len(allocated[-1]) != m: # Check if the number of allocated resources
matches the number of resources
print("Error: Number of allocated resources doesn't match the number
of resources.") exit(1) max_need = []
print("Enter the maximum number of resources needed by each process:")
for i in range(n): max_need.append(list(map(int, input(f"For
process {processes[i]}:
").split()))) if len(max_need[-1]) != m: # Check if the number of
maximum needed resources matches the number of resources
print("Error: Number of maximum needed resources doesn't match the number of
resources.")
exit(1)
main() Output:
Fr. CRCE Operating Systems Lab 2023-2024
References:
https://www.javatpoint.com/os-resource-allocation-graph https://www.javatpoint.com/os-deadlock-
avoidance