Loading…
OS · Deadlock & memory · Program 33 · In the record
Write shell script for the following memory management methods, First Fit, Best Fit, and Worst fit.
1#!/bin/bash2 3echo "Enter number of memory blocks:"4read nb5echo "Enter size of each block:"6for (( j = 0; j < nb; j++ ))7do8 read block[j]9done10 11echo "Enter number of processes:"12read np13echo "Enter size of each process:"14for (( i = 0; i < np; i++ ))15do16 read proc[i]17done18 19# $1 is the method name: First Fit, Best Fit or Worst Fit20allocate()21{22 # Every method starts again with all the blocks free23 for (( j = 0; j < nb; j++ ))24 do25 hole[j]=${block[j]}26 done27 28 echo29 echo "---------- $1 ----------"30 printf "%-10s%-8s%-8s%s\n" "Process" "Size" "Block" "Left"31 32 for (( i = 0; i < np; i++ ))33 do34 pick=-135 for (( j = 0; j < nb; j++ ))36 do37 if (( hole[j] >= proc[i] ))38 then39 if (( pick == -1 ))40 then41 pick=$j42 # First Fit stops at the first block that is big enough43 if [ "$1" = "First Fit" ]44 then45 break46 fi47 elif [ "$1" = "Best Fit" ] && (( hole[j] < hole[pick] ))48 then49 pick=$j # smallest block that fits50 elif [ "$1" = "Worst Fit" ] && (( hole[j] > hole[pick] ))51 then52 pick=$j # largest block that fits53 fi54 fi55 done56 57 if (( pick == -1 ))58 then59 printf "%-10s%-8s%s\n" "P$((i + 1))" "${proc[i]}" "Not allocated"60 else61 hole[pick]=$((hole[pick] - proc[i]))62 printf "%-10s%-8s%-8s%s\n" "P$((i + 1))" "${proc[i]}" "B$((pick + 1))" "${hole[pick]}"63 fi64 done65}66 67allocate "First Fit"68allocate "Best Fit"69allocate "Worst Fit"5 ⏎ 100 ⏎ 500 ⏎ 200 ⏎ 300 ⏎ 600 ⏎ 4 ⏎ 212 ⏎ 417 ⏎ 112 ⏎ 426Enter number of memory blocks: 5 Enter size of each block: 100 500 200 300 600 Enter number of processes: 4 Enter size of each process: 212 417 112 426 ---------- First Fit ---------- Process Size Block Left P1 212 B2 288 P2 417 B5 183 P3 112 B2 176 P4 426 Not allocated ---------- Best Fit ---------- Process Size Block Left P1 212 B4 88 P2 417 B2 83 P3 112 B3 88 P4 426 B5 174 ---------- Worst Fit ---------- Process Size Block Left P1 212 B5 388 P2 417 B2 83 P3 112 B5 276 P4 426 Not allocated
Run program 33 in your browser
bash · just-bash. Change the code or the input, run it, break it, and see what happens.