0% found this document useful (0 votes)
7 views12 pages

Memory & File Management Simulation

Uploaded by

chillwithap
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views12 pages

Memory & File Management Simulation

Uploaded by

chillwithap
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CS 305 Assignment Submission: Memory &

File Management Simulation

1. Introduction

This assignment simulates basic operating system functionality by managing both memory and
disk operations. The solution demonstrates:

 Memory Management:
An 8 KB memory is divided into 1 KB pages (8 pages total). Six processes, each with a
start time, memory requirement, and duration, are simulated. Processes allocate memory
when starting and free it when they end (entering a "sleep" state).
 File Management (Linked Allocation):
A simulated disk with 32 blocks is used (to support block numbers such as 28, 15, 12,
19). A file named "MyFile" is created with linked allocation using these blocks, read (to
simulate transfer to memory), and then deleted—freeing its disk blocks.

The solution is Done in Python, with clear inline comments and a straightforward timeline
simulation of process and file events.

2. Implementation Overview

Memory Management

 Memory: 8 KB total with 1 KB pages → 8 pages.


 Allocation: Uses a simple first-fit algorithm to allocate contiguous pages.
 Processes: Six processes are scheduled to start and end at different times. Memory is
allocated on start and freed on end.

File Management
 Disk: Simulated with 32 blocks.
 Linked Allocation: The file "MyFile" is stored in blocks [28, 15, 12, 19].
 File Operations: The file is created, read, and later deleted to free the allocated blocks.

Timeline

 Both process events and file events are merged into one timeline and sorted by time. For
each event, the current memory or disk state is printed.

3. Complete Python Code


#!/usr/bin/env python3

import math

# ------------------------

# Process Representation

# ------------------------

class Process:

def __init__(self, pid, start_time, mem_required_kb, duration):

[Link] = pid # Unique process identifier

self.start_time = start_time # When the process starts

self.mem_required_kb = mem_required_kb # Memory needed in KB

[Link] = duration # Duration of execution

self.end_time = start_time + duration # End time


[Link] = 'new' # Initial state

# ------------------------

# Memory Manager

# ------------------------

class MemoryManager:

"""

Simulates 8KB of memory divided into 1KB pages (8 total pages).

Uses a first-fit allocation strategy to allocate contiguous pages.

"""

def __init__(self, total_kb=8, page_kb=1):

self.total_kb = total_kb

self.page_kb = page_kb

self.num_pages = total_kb // page_kb # Should be 8 pages

[Link] = [None] * self.num_pages # None indicates a free page

def allocate(self, pid, size_kb):

"""Allocate contiguous pages for process pid."""

needed = [Link](size_kb / self.page_kb)

run = 0

for i in range(self.num_pages):

if [Link][i] is None:

run += 1
else:

run = 0

if run == needed:

start = i - needed + 1

for j in range(start, start + needed):

[Link][j] = pid

return True

return False

def free(self, pid):

"""Free all pages allocated to process pid."""

for i in range(self.num_pages):

if [Link][i] == pid:

[Link][i] = None

def __str__(self):

"""Return a string representation of memory (PID or '.' if free)."""

return ' | '.join(str(p) if p is not None else '.' for p in [Link])

# ------------------------

# File & Disk Manager

# ------------------------

class FileEntry:
def __init__(self, name, blocks):

[Link] = name

[Link] = blocks # Linked list of disk blocks allocated to the file

class DiskManager:

"""

Simulates a disk with 32 blocks. Each block is considered 1KB.

Implements linked allocation for files.

"""

def __init__(self, total_blocks=32):

self.block_map = [False] * total_blocks # False indicates a free block

[Link] = {} # Dictionary to store files by name

def create_file(self, filename, block_list):

"""Create a file with a given list of disk blocks."""

for b in block_list:

if b < 0 or b >= len(self.block_map) or self.block_map[b]:

print(f"[DISK] Cannot create '{filename}': block {b} invalid or in use.")

return

for b in block_list:

self.block_map[b] = True

[Link][filename] = FileEntry(filename, block_list)

print(f"[DISK] Created file '{filename}' with blocks {block_list}")


def read_file(self, filename):

"""Simulate reading a file by printing its disk blocks."""

if filename not in [Link]:

print(f"[DISK] File '{filename}' not found.")

return

print(f"[DISK] Reading file '{filename}' -> blocks {[Link][filename].blocks}")

def delete_file(self, filename):

"""Delete a file and free its disk blocks."""

if filename not in [Link]:

print(f"[DISK] File '{filename}' not found.")

return

for b in [Link][filename].blocks:

self.block_map[b] = False

print(f"[DISK] Deleted file '{filename}', freed blocks {[Link][filename].blocks}")

del [Link][filename]

def __str__(self):

"""Return a string showing disk block allocation ('A' for allocated, 'F' for free)."""

return ''.join('A' if x else 'F' for x in self.block_map)

# ------------------------
# Main Simulation

# ------------------------

if __name__ == "__main__":

# Define 6 processes: (pid, start_time, memory_needed in KB, duration)

processes = [

Process(1, 0, 2, 3),

Process(2, 1, 1, 4),

Process(3, 2, 2, 3),

Process(4, 5, 2, 2),

Process(5, 6, 1, 3),

Process(6, 7, 2, 2),

# Build process events: each process generates a start event (+1) and an end event (-1)

events = []

for p in processes:

[Link]((p.start_time, [Link], +1, p.mem_required_kb))

[Link]((p.end_time, [Link], -1, p.mem_required_kb))

# Sort events by time; in case of tie, end events (-1) come before start events (+1)

[Link](key=lambda x: (x[0], x[2]))

# Define file events:

# - At time 0.5, create "MyFile" in blocks [28, 15, 12, 19]


# - At time 2, read "MyFile"

# - At time 6, delete "MyFile"

file_events = [

(0.5, 'create', 'MyFile', [28, 15, 12, 19]),

(2, 'read', 'MyFile', None),

(6, 'delete', 'MyFile', None),

# Merge process events and file events into a single timeline.

# Format for process events: ('proc', time, pid, event_type, mem_needed)

# Format for file events: ('file', time, operation, filename, block_list)

timeline = []

for e in events:

[Link](('proc', e[0], e[1], e[2], e[3]))

for fe in file_events:

[Link](('file', fe[0], fe[1], fe[2], fe[3]))

# Sort timeline by time; if tie, process events come before file events

[Link](key=lambda x: (x[1], 0 if x[0] == 'proc' else 1))

# Create memory and disk managers

mem = MemoryManager(total_kb=8, page_kb=1)

disk = DiskManager(total_blocks=32)
print("=== Simulation Start ===\n")

current_time = 0

for ev in timeline:

ev_type = ev[0]

t = ev[1]

if t > current_time:

current_time = t

if ev_type == 'proc':

# Process event: ( 'proc', time, pid, event_type, mem_needed )

pid, etype, mem_needed = ev[2], ev[3], ev[4]

if etype == +1:

# Process start: allocate memory

success = [Link](pid, mem_needed)

state = "ALLOCATED" if success else "FAILED"

print(f"Time={t:.1f}: START Process {pid} (needs {mem_needed}KB) -> {state}")

else:

# Process end: free memory

[Link](pid)

print(f"Time={t:.1f}: END Process {pid} -> Memory Freed (Sleep)")

print(" Memory:", mem)

else:

# File event: ( 'file', time, operation, filename, block_list )


op, filename, blocks = ev[2], ev[3], ev[4]

if op == 'create':

disk.create_file(filename, blocks)

elif op == 'read':

disk.read_file(filename)

elif op == 'delete':

disk.delete_file(filename)

print(" Disk:", disk)

print("\n=== Simulation Complete ===")

print("Final Memory State:", mem)

print("Final Disk State:", disk)

print("All processes are now in 'Sleep' state.\n")

# ------------------------

# References:

# Silberschatz, A., Galvin, P. B., & Gagne, G. (2018). Operating System Concepts (10th ed.).
Wiley.

# Tanenbaum, A. S., & Bos, H. (2015). Modern Operating Systems (4th ed.). Pearson.

4. Sample Output
=== Simulation Start ===

Time=0.0: START Process 1 (needs 2KB) -> ALLOCATED

Memory: 1 | 1 | . | . | . | . | . | .
Time=0.5:

[DISK] Created file 'MyFile' with blocks [28, 15, 12, 19]

Disk: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAAFFFFFFFFFFFFFFF

Time=1.0: START Process 2 (needs 1KB) -> ALLOCATED

Memory: 1 | 1 | 2 | . | . | . | . | .

Time=2.0:

[DISK] Reading file 'MyFile' -> blocks [28, 15, 12, 19]

Disk: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAAFFFFFFFFFFFFFFF

Time=2.0: START Process 3 (needs 2KB) -> ALLOCATED

Memory: 1 | 1 | 2 | 3 | 3 | . | . | .

Time=3.0: END Process 1 -> Memory Freed (Sleep)

Memory: . | . | 2 | 3 | 3 | . | . | .

Time=5.0: END Process 2 -> Memory Freed (Sleep)

Memory: . | . | . | 3 | 3 | . | . | .

Time=5.0: START Process 4 (needs 2KB) -> ALLOCATED

Memory: 4 | 4 | . | 3 | 3 | . | . | .

Time=6.0:

[DISK] Deleted file 'MyFile', freed blocks [28, 15, 12, 19]

Disk: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF

Time=6.0: START Process 5 (needs 1KB) -> ALLOCATED

Memory: 4 | 4 | 5 | 3 | 3 | . | . | .

Time=7.0: END Process 4 -> Memory Freed (Sleep)

Memory: . | . | 5 | 3 | 3 | . | . | .
Time=7.0: START Process 6 (needs 2KB) -> ALLOCATED

Memory: 6 | 6 | 5 | 3 | 3 | . | . | .

Time=9.0: END Process 3 -> Memory Freed (Sleep)

Memory: 6 | 6 | 5 | . | . | . | . | .

Time=9.0: END Process 5 -> Memory Freed (Sleep)

Memory: 6 | 6 | . | . | . | . | . | .

Time=9.0: END Process 6 -> Memory Freed (Sleep)

Memory: . | . | . | . | . | . | . | .

=== Simulation Complete ===

Final Memory State: . | . | . | . | . | . | . | .

Final Disk State: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF

All processes are now in 'Sleep' state.

5. References
 References:

o Silberschatz, A., Galvin, P. B., & Gagne, G. (2018). Operating System Concepts
(10th ed.). Wiley.

o Tanenbaum, A. S., & Bos, H. (2015). Modern Operating Systems (4th ed.).
Pearson.

You might also like