Loading…
OS · Deadlock & memory · Program 32 · In the record
Write shell script for Bankers Algorithm.
1#!/bin/bash2 3echo "Enter number of processes:"4read n5echo "Enter number of resource types:"6read m7 8# 2D matrices are stored in 1D arrays: row i, column j is at index i * m + j9echo "Enter Allocation matrix (one row per process):"10for (( i = 0; i < n; i++ ))11do12 read line13 j=014 for x in $line15 do16 alloc[i * m + j]=$x17 j=$((j + 1))18 done19done20 21echo "Enter Max matrix (one row per process):"22for (( i = 0; i < n; i++ ))23do24 read line25 j=026 for x in $line27 do28 max[i * m + j]=$x29 j=$((j + 1))30 done31done32 33echo "Enter Available resources:"34read line35j=036for x in $line37do38 work[j]=$x39 j=$((j + 1))40done41 42# Need = Max - Allocation43echo44echo "Need matrix:"45for (( i = 0; i < n; i++ ))46do47 row=""48 for (( j = 0; j < m; j++ ))49 do50 need[i * m + j]=$((max[i * m + j] - alloc[i * m + j]))51 row="$row ${need[i * m + j]}"52 done53 echo "P$i:$row"54 finish[i]=055done56 57# Safety algorithm58seq=""59count=060found=161while (( count < n && found == 1 ))62do63 found=064 for (( i = 0; i < n; i++ ))65 do66 if (( finish[i] == 0 ))67 then68 ok=169 for (( j = 0; j < m; j++ ))70 do71 if (( need[i * m + j] > work[j] ))72 then73 ok=074 fi75 done76 77 if (( ok == 1 ))78 then79 # Process i can finish, so it gives back what it holds80 for (( j = 0; j < m; j++ ))81 do82 work[j]=$((work[j] + alloc[i * m + j]))83 done84 finish[i]=185 seq="$seq P$i"86 count=$((count + 1))87 found=188 fi89 fi90 done91done92 93echo94if (( count == n ))95then96 echo "The system is in a SAFE state."97 echo "Safe sequence:$seq"98else99 echo "The system is in an UNSAFE state (deadlock possible)."100fi5 ⏎ 3 ⏎ 0 1 0 ⏎ 2 0 0 ⏎ 3 0 2 ⏎ 2 1 1 ⏎ 0 0 2 ⏎ 7 5 3 ⏎ 3 2 2 ⏎ 9 0 2 ⏎ 2 2 2 ⏎ 4 3 3 ⏎ 3 3 2Enter number of processes: 5 Enter number of resource types: 3 Enter Allocation matrix (one row per process): 0 1 0 2 0 0 3 0 2 2 1 1 0 0 2 Enter Max matrix (one row per process): 7 5 3 3 2 2 9 0 2 2 2 2 4 3 3 Enter Available resources: 3 3 2 Need matrix: P0: 7 4 3 P1: 1 2 2 P2: 6 0 0 P3: 0 1 1 P4: 4 3 1 The system is in a SAFE state. Safe sequence: P1 P3 P4 P0 P2
Run program 32 in your browser
bash · just-bash. Change the code or the input, run it, break it, and see what happens.