0% found this document useful (0 votes)
14 views

OS LAB NEW-1

The document contains multiple examples of I/O programming and scheduling algorithms in Python, including process creation, file operations, Shortest Job First, First Come First Served, Round Robin, and Priority Scheduling. Each example provides a program with input and output details, demonstrating how to manage processes and handle file data. The algorithms are implemented to calculate waiting times, turnaround times, and average times for various scheduling strategies.

Uploaded by

nathangokul54
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

OS LAB NEW-1

The document contains multiple examples of I/O programming and scheduling algorithms in Python, including process creation, file operations, Shortest Job First, First Come First Served, Round Robin, and Priority Scheduling. Each example provides a program with input and output details, demonstrating how to manage processes and handle file data. The algorithms are implemented to calculate waiting times, turnaround times, and average times for various scheduling strategies.

Uploaded by

nathangokul54
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

EX NO : 1 BASIC I/O PROGRAMMING – PROCESS CREATION

DATE : 16.12.24

PROGRAM

from multiprocessing import Process

import os

def info(title):

print(title)

# Print module name, parent process, and process id

print('module name:', __name__)

print('parent process:', os.getppid())

print('process id:', os.getpid())

def f(name):

info('function f')

print('hello', name)

if __name__ == '__main__':

info('main line')

# Create the Process object and start it

p = Process(target=f, args=('bob',))

p.start()

p.join()

# Print child process information

print("Child Process Name:", p.name)

print("Child Process ID:", p.pid)


OUTPUT

module name: __main__

parent process: 12345 # Example Process ID

process id: 12346 # Example Process ID

main line

function f

hello bob

Child Process Name: Process-1

Child Process ID: 12347

# Example Process ID
EX NO : 1(b) BASIC I/O PROGRAMMING – FILE OPERATION

DATE : 16.12.24

PROGRAM:

# Program to show various ways to read and write data in a file.

# Open file in write mode

file1 = open("myfile.txt", "w")

L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# \n is placed to indicate EOL (End of Line)

file1.write("Hello \n")

file1.writelines(L)

file1.close()

# To change file access modes (read and write)

file1 = open("myfile.txt", "r+")

# Output of read function

print("Output of Read function is:")

print(file1.read()) # Read the entire content of the file

print()

# Seek to the beginning of the file (byte 0)

file1.seek(0)

# Output of readline function

print("Output of Readline function is:")

print(file1.readline()) # Reads the first line

print()

# Seek again to the beginning of the file

file1.seek(0)

# Output of read function with a specified number of characters (9 characters in this case)

print("Output of Read(9) function is:")

print(file1.read(9)) # Reads first 9 characters


print()

# Seek again to the beginning of the file

file1.seek(0)

# Output of readline function with a specified number of characters (9 characters in this case)

print("Output of Readline(9) function is:")

print(file1.readline(9)) # Reads the first 9 characters of the first line

print()

# Seek again to the beginning of the file

file1.seek(0)

# Output of readlines function

print("Output of Readlines function is:")

print(file1.readlines()) # Reads all lines and returns a list

print()

# Close the file

file1.close()
OUTPUT

Output of Read function is:

Hello

This is Delhi

This is Paris

This is London

Output of Readline function is:

Hello

Output of Read(9) function is:

This is D

Output of Readline(9) function is:

This is

Output of Readlines function is:

['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
EX NO: 2 SHORTEST JOB FIRST ALGORITHM

DATE : 03.01.25

PROGRAM

# Python3 program for Shortest Job First (Preemptive) algorithm

n = int(input('Enter no of processes: '))

abt = [0] * n # Burst time for each process

at = [0] * n # Arrival time for each process

bt = [] # List of processes [burst_time, arrival_time, process_index]

# Input burst time and arrival time for each process

for i in range(n):

abt[i] = int(input(f'Enter the burst time for process {i+1}: '))

at[i] = int(input(f'Enter the arrival time for process {i+1}: '))

bt.append([abt[i], at[i], i])

# Sort by arrival time to simulate preemptive behavior

bt.sort(key=lambda x: x[1])

# Variables to track times

sumbt = sum(abt)

ct = [0] * n # Completion times

tat = [0] * n # Turnaround times

wt = [0] * n # Waiting times

# Preemptive SJF (Shortest Job First)

ll = [] # List to store the execution details

current_time = 0 # Start time is 0

completed = 0 # Count of completed processes

# While there are unfinished processes

while completed < n:

# List of processes that have arrived by current_time

ready_queue = [proc for proc in bt if proc[1] <= current_time and proc[0] > 0]

if ready_queue:

# Sort by burst time (smallest burst time first)


ready_queue.sort(key=lambda x: x[0])

# Pick the process with the shortest burst time

shortest = ready_queue[0]

shortest_index = bt.index(shortest)

# Simulate one unit of time for this process

bt[shortest_index][0] -= 1 # Decrement burst time by 1

current_time += 1 # Increment the current time

# If the process is completed

if bt[shortest_index][0] == 0:

ct[shortest_index] = current_time # Completion time

completed += 1 # Increase completed process count

ll.append([bt[shortest_index], current_time]) # Store process execution details

else:

current_time += 1 # If no process is ready, increment time

# Calculate turnaround and waiting times

for i in range(n):

tat[i] = ct[i] - at[i] # Turnaround time = Completion time - Arrival time

wt[i] = tat[i] - abt[i] # Waiting time = Turnaround time - Burst time

# Output the results

print('PNo\tBT\tAT\tCT\tTAT\tWT')

for i in range(n):

print(f"{i+1}\t{abt[i]}\t{at[i]}\t{ct[i]}\t{tat[i]}\t{wt[i]}")

# Calculate average waiting and turnaround time

print(f'Average Waiting Time = {sum(wt)/n}')

print(f'Average Turnaround Time = {sum(tat)/n}')


INPUT

Enter no of processes: 4

Enter the burst time for process 1: 6

Enter the arrival time for process 1: 2

Enter the burst time for process 2: 8

Enter the arrival time for process 2: 0

Enter the burst time for process 3: 7

Enter the arrival time for process 3: 1

Enter the burst time for process 4: 3

Enter the arrival time for process 4: 3

OUTPUT:

PNo BT AT CT TAT WT

1 6 2 14 12 6

2 8 0 22 22 14

3 7 1 20 19 12

4 3 3 16 13 10

Average Waiting Time = 10.5

Average Turnaround Time = 14.0


EX NO: 3 FIRST COME FIRST SERVED ALGORITHM

DATE : 20.01.25

PROGRAM

# Python3 program for Shortest Job First (Preemptive) algorithm

n = int(input('Enter no of processes: '))

abt = [0] * n # Burst time for each process

at = [0] * n # Arrival time for each process

bt = [] # List of processes [burst_time, arrival_time, process_index]

# Input burst time and arrival time for each process

for i in range(n):

abt[i] = int(input(f'Enter the burst time for process {i+1}: '))

at[i] = int(input(f'Enter the arrival time for process {i+1}: '))

bt.append([abt[i], at[i], i])

# Sort by arrival time to simulate preemptive behavior

bt.sort(key=lambda x: x[1])

# Variables to track times

sumbt = sum(abt)

ct = [0] * n # Completion times

tat = [0] * n # Turnaround times

wt = [0] * n # Waiting times

# Preemptive SJF (Shortest Job First)

ll = [] # List to store the execution details

current_time = 0 # Start time is 0

completed = 0 # Count of completed processes

# While there are unfinished processes

while completed < n:

# List of processes that have arrived by current_time

ready_queue = [proc for proc in bt if proc[1] <= current_time and proc[0] > 0]

if ready_queue:
# Sort by burst time (smallest burst time first)

ready_queue.sort(key=lambda x: x[0])

# Pick the process with the shortest burst time

shortest = ready_queue[0]

shortest_index = bt.index(shortest)

# Simulate one unit of time for this process

bt[shortest_index][0] -= 1 # Decrement burst time by 1

current_time += 1 # Increment the current time

# If the process is completed

if bt[shortest_index][0] == 0:

ct[shortest_index] = current_time # Completion time

completed += 1 # Increase completed process count

ll.append([bt[shortest_index], current_time]) # Store process execution details

else:

current_time += 1 # If no process is ready, increment time

# Calculate turnaround and waiting times

for i in range(n):

tat[i] = ct[i] - at[i] # Turnaround time = Completion time - Arrival time

wt[i] = tat[i] - abt[i] # Waiting time = Turnaround time - Burst time

# Output the results

print('PNo\tBT\tAT\tCT\tTAT\tWT')

for i in range(n):

print(f"{i+1}\t{abt[i]}\t{at[i]}\t{ct[i]}\t{tat[i]}\t{wt[i]}")

# Calculate average waiting and turnaround time

print(f'Average Waiting Time = {sum(wt)/n}')

print(f'Average Turnaround Time = {sum(tat)/n}')


INPUT

Enter no of processes: 4

Enter the burst time for process 1: 6

Enter the arrival time for process 1: 2

Enter the burst time for process 2: 8

Enter the arrival time for process 2: 0

Enter the burst time for process 3: 7

Enter the arrival time for process 3: 1

Enter the burst time for process 4: 3

Enter the arrival time for process 4: 3

OUTPUT

Processes Burst time Waiting time Turn around time

1 24 0 24

2 3 24 27

3 3 27 30

Average waiting time = 17.0

Average turn around time = 23.666666666666668


EX NO : 4(a) ROUND POBIN SCHEDULING ALGORITHM

DATE :20.01.25

PROGRAM

# Python3 program for implementation of RR scheduling

# Function to find waiting time for each process

def findWaitingTime(processes, n, bt, wt, quantum):

rem_bt = [0] * n # Remaining burst time for each process

for i in range(n):

rem_bt[i] = bt[i]

t = 0 # Current time

while True:

done = True

for i in range(n):

if rem_bt[i] > 0:

done = False # There is a pending process

if rem_bt[i] > quantum:

t += quantum

rem_bt[i] -= quantum

else:

t = t + rem_bt[i]

wt[i] = t - bt[i]

rem_bt[i] = 0

if done:

break

# Function to find turnaround time for each process

def findTurnAroundTime(processes, n, bt, wt, tat):

for i in range(n):

tat[i] = bt[i] + wt[i] # Turnaround time = Burst time + Waiting time

# Function to calculate and display average times


def findavgTime(processes, n, bt, quantum):

wt = [0] * n # Initialize waiting time list

tat = [0] * n # Initialize turnaround time list

findWaitingTime(processes, n, bt, wt, quantum)

findTurnAroundTime(processes, n, bt, wt, tat)

print("Processes Burst Time Waiting Time Turn-Around Time")

total_wt = 0

total_tat = 0

for i in range(n):

total_wt += wt[i]

total_tat += tat[i]

print(f" {i + 1} \t\t {bt[i]} \t\t {wt[i]} \t\t {tat[i]}")

print("\nAverage waiting time = %.5f" % (total_wt / n))

print("Average turn around time = %.5f" % (total_tat / n))

# Driver code

if __name__ == "__main__":

# Process id's

proc = [1, 2, 3]

n=3

# Burst time of all processes

burst_time = [24, 3, 3]

# Time quantum

quantum = 4

# Call the function to calculate average times

findavgTime(proc, n, burst_time, quantum)


OUTPUT

Processes Burst Time Waiting Time Turn-Around Time

1 24 0 24

2 3 24 27

3 3 27 30

Average waiting time = 17.00000

Average turn around time = 23.66667


EX NO : 4(b) PRIORITY SCHEDULING ALGORITHM

DATE : 28.01.25

PROGRAM

# Python3 program for implementation of Priority Scheduling

# Function to find waiting time for each process

def findWaitingTime(processes, n, wt):

wt[0] = 0 # Waiting time for the first process is always 0

for i in range(1, n):

wt[i] = processes[i - 1][1] + wt[i - 1] # Waiting time = sum of burst times of previous
processes

# Function to find turnaround time for each process

def findTurnAroundTime(processes, n, wt, tat):

for i in range(n):

tat[i] = processes[i][1] + wt[i] # Turnaround time = Burst time + Waiting time

# Function to calculate and display average waiting time and average turnaround time

def findavgTime(processes, n):

wt = [0] * n # Initialize waiting time list

tat = [0] * n # Initialize turnaround time list

findWaitingTime(processes, n, wt)

findTurnAroundTime(processes, n, wt, tat)

print("\nProcesses \tBurst Time \tWaiting Time \tTurn-Around Time")

total_wt = 0

total_tat = 0

for i in range(n):

total_wt += wt[i]

total_tat += tat[i]

print(f" {processes[i][0]} \t\t {processes[i][1]} \t\t {wt[i]} \t\t {tat[i]}")


print(f"\nAverage waiting time = {total_wt / n:.5f}")

print(f"Average turn around time = {total_tat / n:.5f}")

# Priority Scheduling function

def priorityScheduling(proc, n):

# Sort processes by priority (higher priority first)

proc = sorted(proc, key=lambda proc: proc[2], reverse=True)

print("Order in which processes get executed:")

for i in proc:

print(i[0], end=" ")

findavgTime(proc, n)

# Driver code

if __name__ == "__main__":

# Process id's [id, burst time, priority]

proc = [[1, 10, 1], # Process 1: burst time = 10, priority = 1

[2, 5, 0], # Process 2: burst time = 5, priority = 0

[3, 8, 1]] # Process 3: burst time = 8, priority = 1

n = len(proc) # Number of processes

print("Priority Scheduling Algorithm")

priorityScheduling(proc, n)
OUTPUT

Priority Scheduling Algorithm

Order in which processes get executed:

132

Processes Burst Time Waiting Time Turn-Around Time

1 10 0 10

3 8 10 18

2 5 18 23

Average waiting time = 9.33333

Average turn around time = 17.00000


EX NO : 5 IMPLEMENT READER /WRITER PROBLEM USING SEMAPHORE

DATE : 28.01.25

PROGRAM:

import threading

import time

class ReaderWriterProblem:

def __init__(self):

self.mutex = threading.Semaphore(1) # Mutex for synchronizing reader count

self.wrt = threading.Semaphore(1) # Semaphore for writing access

self.r_c = 0 # Number of active readers

def reader(self):

while True:

self.mutex.acquire() # Enter critical section to update reader count

self.r_c += 1 # A new reader is entering

if self.r_c == 1: # First reader, block writers

self.wrt.acquire()

self.mutex.release() # Exit critical section

# Reading operation

print(f"\nReader {self.r_c} is reading")

time.sleep(2) # Simulate reading time

self.mutex.acquire() # Enter critical section to update reader count

self.r_c -= 1 # A reader is leaving

if self.r_c == 0: # Last reader, allow writers to proceed

self.wrt.release()

self.mutex.release() # Exit critical section

time.sleep(3) # Simulate some delay before next reading

def writer(self):

while True:

self.wrt.acquire() # Only one writer at a time, block other writers


print("Writing data.")

print("-" * 20)

self.wrt.release() # Writer done, allow other writers to enter

time.sleep(3) # Simulate writing time

def main(self):

t1 = threading.Thread(target=self.reader)

t2 = threading.Thread(target=self.writer)

t3 = threading.Thread(target=self.reader)

t4 = threading.Thread(target=self.reader)

t5 = threading.Thread(target=self.reader)

t6 = threading.Thread(target=self.writer)

t1.start()

t2.start()

t3.start()

t4.start()

t5.start()

t6.start()

if __name__ == "__main__":

c = ReaderWriterProblem()

c.main()
OUTPUT

Reader 1 is
reading Reader 2
is reading Reader
4 is reading
Reader 3 is
reading Wrting
data.....

Wrting data.....

Reader 1 is
reading Reader 3
is reading Reader
2 is reading
Reader 4 is
reading

Wrting data.....

Wrting data.....
EX NO : 6 IMPLEMENT BANKER’S ALGORITHM FOR DEADLOCK AVOIDANCE

DATE : 05.02.25

PROGRAM:

# Number of processes and resources

P = 5 # Processes

R = 3 # Resources

# Function to calculate the need matrix

def calculateNeed(need, maxm, allot):

for i in range(P):

for j in range(R):

need[i][j] = maxm[i][j] - allot[i][j]

# Function to check if the system is in a safe state

def isSafe(processes, avail, maxm, allot):

# Calculate need matrix

need = []

for i in range(P):

l = []

for j in range(R):

l.append(0)

need.append(l)

calculateNeed(need, maxm, allot)

# To track which processes have finished

finish = [0] * P

# Safe sequence array

safeSeq = [0] * P

# Available resources

work = [0] * R

for i in range(R):

work[i] = avail[i]
count = 0 # Count of processes that have been allocated

# Try to find a safe sequence

while count < P:

found = False

for p in range(P):

if finish[p] == 0:

# Check if process p's needs can be met with available resources

for j in range(R):

if need[p][j] > work[j]:

break

else:

# Process p can finish, so allocate resources to it

for k in range(R):

work[k] += allot[p][k]

safeSeq[count] = p

count += 1

finish[p] = 1

found = True

break

if not found:

# If no process could proceed, the system is not in a safe state

print("System is not in a safe state.")

return False

print("System is in a safe state.")

print("Safe sequence is:", safeSeq)

return True

# Driver code

if __name__ == "__main__":

# Available instances of resources

avail = [3, 3, 2]
# Maximum resources that can be allocated to each process

maxm = [

[7, 5, 3],

[3, 2, 2],

[9, 0, 2],

[2, 2, 2],

[4, 3, 3]

# Resources allocated to each process

allot = [

[0, 1, 0],

[2, 0, 0],

[3, 0, 2],

[2, 1, 1],

[0, 0, 2]

# Check if the system is in a safe state or not

isSafe(range(P), avail, maxm, allot)

OUTPUT:

System is in safe state.


Safe sequence is: 1 3 4 0
2
EX NO : 7 FIRST IN FIRST OUT ALGORITHM
DATE : 05.02.25

PROGRAM:

from queue import Queue


# Function to find page faults using FIFO
def pageFaults(pages, n, capacity):
# Set to store pages currently in memory
s = set()
# Queue to keep track of the order of pages
indexes = Queue()
# Counter for page faults
page_faults = 0
# Traverse through the given pages
for i in range(n):
# If there's space in memory (less than capacity)
if len(s) < capacity:
if pages[i] not in s:
s.add(pages[i])
page_faults += 1
indexes.put(pages[i])
else:
# If the page is not already in memory
if pages[i] not in s:
# Remove the page that has been in memory the longest
val = indexes.queue[0]
indexes.get() # Remove the oldest page
s.remove(val) # Remove from the set
s.add(pages[i]) # Add new page to memory
indexes.put(pages[i]) # Add new page to the queue
page_faults += 1

# Print the current state of the pages in memory


print(s, end=" ")

# Print the final page fault count


print("\nPage Fault Count:", page_faults)
return page_faults

# Driver code
if __name__ == '__main__':
pages = [3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4] # Given page reference string
n = len(pages) # Total number of pages
capacity = 3 # Memory capacity (number of frames)

print("Total Page Fault Count:", pageFaults(pages, n, capacity))


OUTPUT:

{3} {2, 3} {1, 2, 3} {0, 1, 2} {0, 1, 3} {0, 2, 3} {2, 3, 4} {2, 3, 4} {2, 3, 4} {1, 2, 4} {0, 1, 4} {0, 1, 4}
Page Fault Count: 9
Total Page Fault Count: 9
EX NO : 8 LEAST RECENTLY USED ALGORITHM
DATE : 19.02.25

PROGRAM:

# Python program for LRU (Least Recently Used) Page Replacement Algorithm

# Driver code
capacity = 3 # The number of frames available in memory
processList = [0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2] # Given page reference string

# To store the current pages in memory


s = []
pageFaults = 0

# Traverse through the page reference list


for i in processList:
# If the page is not in memory
if i not in s:
# If memory is full, remove the least recently used page (leftmost page)
if len(s) == capacity:
s.pop(0) # Remove the first element (LRU)
s.append(i) # Add the current page to memory
pageFaults += 1 # Increment page fault count
else:
# If page is already in memory, move it to the right (most recently used)
s.remove(i)
s.append(i)

# Print the current state of the memory (pages in memory)


print(s, end=" ")

# Print the total page fault count


print("\nTotal Page Faults:", pageFaults)

OUTPUT:

[0] [0, 1] [0, 1, 2] [0, 1, 2] [1, 2, 0] [2, 0, 3] [0, 3, 2] [0, 3, 2] [3, 2, 0] [2, 0, 3] [0, 3, 2] [0, 3, 2]
Total Page Faults: 9
EX NO : 9(a) IMPLEMENT FIRST FIT ALGORITHM FOR MEMORY MANAGEMENT
DATE : 19.02.25

PROGRAM:

# Python3 program for First Fit Memory Management algorithm

def FirstFit(block_Size, blocks, process_Size, processes):


# List to keep track of allocation (-1 means not allocated)
allocate = [-1] * processes

# List to keep track of which blocks are occupied


occupied = [False] * blocks

# Loop over each process


for i in range(processes):
# Try to find a block for the current process
for j in range(blocks):
if not occupied[j] and block_Size[j] >= process_Size[i]:
# Assign the block j to process i
allocate[i] = j
occupied[j] = True
break

# Print the allocation result


print("Process No.\tProcess Size\t\tBlock No.")
for i in range(processes):
print(f"{i + 1}\t\t{process_Size[i]}\t\t\t", end="")
if allocate[i] != -1:
print(allocate[i] + 1) # Adding 1 to block index to match human-readable format
else:
print("Not Allocated")
# Driver code
block_Size = [100, 50, 30, 120, 35] # Memory block sizes
process_Size = [20, 60, 70, 40] # Process sizes
m = len(block_Size) # Number of blocks
n = len(process_Size) # Number of processes

FirstFit(block_Size, m, process_Size, n)
OUTPUT:

Process No. Process Size Block No.


1 20 1
2 60 4
3 70 Not Allocated
4 40 2
EX NO : 9(B) IMPLEMENT BEST FIT ALGORITHM FOR MEMORY MANAGEMENT
DATE : 26.02.25

PROGRAM

# Python3 program for Best Fit Memory Management algorithm

def bestFit(blockSize, m, processSize, n):


# List to store the allocation of each process
allocation = [-1] * n

# Traverse through each process


for i in range(n):
# Variable to store the index of the best block for the process
bestIdx = -1

# Check each block to find the best fit


for j in range(m):
if blockSize[j] >= processSize[i]: # The block is big enough to accommodate the
process
if bestIdx == -1:
bestIdx = j # First block that can accommodate the process
elif blockSize[bestIdx] > blockSize[j]: # Choose the block with the least remaining
space
bestIdx = j

# If a suitable block is found, allocate the block to the process


if bestIdx != -1:
allocation[i] = bestIdx
blockSize[bestIdx] -= processSize[i] # Reduce the block size after allocation

# Print the allocation result


print("Process No. \t Process Size \t\t Block No.")
for i in range(n):

print(f"{i + 1} \t\t {processSize[i]} \t\t", end="")


if allocation[i] != -1:
print(allocation[i] + 1) # Add 1 to the block index for human-readable output
else:
print("Not Allocated")

# Driver code
if __name__ == "__main__":
blockSize = [100, 500, 200, 300, 600] # Memory block sizes
processSize = [212, 417, 112, 426] # Process sizes
m = len(blockSize) # Number of blocks
n = len(processSize) # Number of processes

# Call the BestFit function


bestFit(blockSize, m, processSize, n)
OUTPUT:

Process No. Process Size Block No.


1 212 2
2 417 5
3 112 3
4 426 Not Allocated
EX NO : 9(C) IMPLEMENT WORST FIT ALGORITHM FOR MEMORY MANAGEMENT
DATE : 26.02.25

PROGRAM:

# Python3 program for Worst Fit Memory Management algorithm

def worstFit(blockSize, m, processSize, n):


# List to store the allocation of each process
allocation = [-1] * n

# Traverse through each process


for i in range(n):
# Variable to store the index of the worst block for the process
wstIdx = -1

# Check each block to find the worst fit (largest block that fits)
for j in range(m):
if blockSize[j] >= processSize[i]: # The block is big enough to accommodate the
process
if wstIdx == -1:
wstIdx = j # First block that can accommodate the process
elif blockSize[wstIdx] < blockSize[j]: # Choose the block with the largest size
wstIdx = j

# If a suitable block is found, allocate the block to the process


if wstIdx != -1:
allocation[i] = wstIdx
blockSize[wstIdx] -= processSize[i] # Reduce the block size after allocation

# Print the allocation result


print("Process No. \t Process Size \t\t Block No.")
for i in range(n):
print(f"{i + 1} \t\t {processSize[i]} \t\t", end="")
if allocation[i] != -1:
print(allocation[i] + 1) # Add 1 to the block index for human-readable output
else:
print("Not Allocated")
# Driver code
if __name__ == "__main__":
blockSize = [100, 500, 200, 300, 600] # Memory block sizes
processSize = [212, 417, 112, 426] # Process sizes
m = len(blockSize) # Number of blocks
n = len(processSize) # Number of processes

print("\t\t\tWorst Fit Algorithm")

# Call the WorstFit function


worstFit(blockSize, m, processSize, n)
OUTPUT:

Worst Fit Algorithm

Process No. Process Size Block No.

1 212 2
2 417 5
3 112 4
4 426 Not Allocated
EX NO : 10 INTER PROCESS COMMUNICATION FOR SHARED MEMORY
DATE : 04.03.25

PROGRAM:

# Python3 program for Multiprogramming Shared Memory


from multiprocessing import Process, Value, Array

# Function to modify shared memory


def f(n, a):
n.value = 3.1415927 # Modify the shared value
for i in range(len(a)):
a[i] = -a[i] # Invert the values in the shared array

# Driver code
if __name__ == '__main__':
# Create a shared variable 'num' of type double ('d') initialized to 0.0
num = Value('d', 0.0)

# Create shared arrays 'arr' and 'arr1'


arr = Array('i', range(10)) # Array of integers, initialized to 0-9
arr1 = Array('i', range(1, 20, 2)) # Array of odd integers: 1, 3, 5, ...

print("\t\tIPC using Shared Memory")

# Create and start processes that will modify the shared memory
p1 = Process(target=f, args=(num, arr)) # Process to modify 'num' and 'arr'
p1.start()
p1.join() # Wait for process p1 to finish

p2 = Process(target=f, args=(num, arr1)) # Process to modify 'num' and 'arr1'


p2.start()
p2.join() # Wait for process p2 to finish

# Output the modified values


print(f"Value of num: {num.value}")
print(f"Modified arr: {arr[:]}") # Print the shared array arr
print(f"Modified arr1: {arr1[:]}") # Print the shared array arr1
OUTPUT:

IPC using Shared Memory

Value of num: 3.1415927


Modified arr: [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
Modified arr1: [-1, -3, -5, -7, -9, -11, -13, -15, -17, -19]

You might also like