NEP -OS lAB B.Sc

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6

PART B

PROGRAM B1 PROGRAM B2 PROGRAM B3 PROGRAM B4 PROGRAM B5 PROGRAM B6 . . .
DOWNLOAD PDF FILE OS LAB MANUAL

 
  
  5.Write a python program to demonstrate Best Fit- Memory Management Technique.

class MemoryManager:
    def __init__(self, memory_size):
        self.memory_size = memory_size
        self.memory = [0] * memory_size
        self.processes = {}

 

    def allocate_best_fit(self, process_id, size):
        best_fit_start = None
        best_fit_size = float('inf')

        for i in range(self.memory_size - size + 1):
            if all(self.memory[i + j] == 0 for j in range(size)):
                hole_size = sum(1 for j in range(self.memory_size) if self.memory[j] == 0 and j >= i and j < i + size)
                if hole_size < best_fit_size:
                    best_fit_start = i
                    best_fit_size = hole_size

        if best_fit_start is not None:
            for j in range(size):
                self.memory[best_fit_start + j] = process_id
            self.processes[process_id] = (best_fit_start, size)
            return True
        return False

     

    def print_memory(self):
        print("Memory:")
        for i, val in enumerate(self.memory):
            print(val, end=" ")
            if (i + 1) % 20 == 0:
                print()
        print()

if __name__ == "__main__":
    memory_manager = MemoryManager(100)

   

    # Best fit allocation
    print("Best Fit Allocation:")
    memory_manager.allocate_best_fit("P4", 25)
    memory_manager.print_memory()
 


     

OUTPUT:
P4 P4 P4 P4 P4 P4 P4 P4 P4 P4 P4 P4 P4 P4 P4 P4 P4 P4 P4 P4 
P4 P4 P4 P4 P4 P5 P5 P5 P5 P5 P5 P5 P5 P5 P5 P5 P5 P5 P5 P5 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0