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

extra programs of os

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

extra programs of os

fgxdnkdfjfgfsi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

DATE: EXP NO: PAGE NO:

Deadlock and concurrency with semaphore with Petersons Algorithm


Aim: To implement Deadlock and concurrency with semaphore with Petersons Algorithm
Description:
Peterson's algorithm is a mutual exclusion solution used in concurrent programming to prevent race
conditions. It allows two processes to share a single-use resource without conflicts by ensuring that only one
process can access the critical section at a time. The algorithm relies on two flags and a turn variable to manage
access and avoid deadlocks. It's simple and works well for two processes but isn't scalable for more.
Program:
import threading

# Shared variables
flag = [False, False] # Flag for each process
turn = 0 # Whose turn is it to enter the critical section
shared_resource = 0 # A shared resource (for demonstration)

# Function for Process 0


def process_0():
global shared_resource
flag[0] = True
turn = 1

while flag[1] and turn == 1:


pass # Busy wait

# Critical section
shared_resource += 1
print("Process 0 in critical section: shared_resource =", shared_resource)

# Exit section
flag[0] = False

# Function for Process 1


def process_1():
OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula
DATE: EXP NO: PAGE NO:

global shared_resource
flag[1] = True
turn = 0

while flag[0] and turn == 0:


pass # Busy wait

# Critical section
shared_resource += 1
print("Process 1 in critical section: shared_resource =", shared_resource)

# Exit section
flag[1] = False

# Main function to simulate manual input


def main():
while True:
user_input = input("Enter 0 to run process 0, 1 to run process 1, or q to quit: ")
if user_input == '0':
t0 = threading.Thread(target=process_0)
t0.start()
t0.join() # Wait for thread to finish
elif user_input == '1':
t1 = threading.Thread(target=process_1)
t1.start()
t1.join() # Wait for thread to finish
elif user_input == 'q':
break
else:
print("Invalid input. Please enter 0, 1, or q.")

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

if _name_ == "_main_":
main()
Sample Output:

Enter 0 to run process 0, 1 to run process 1, or q to quit: 0


Process 0 in critical section: shared_resource = 1
Enter 0 to run process 0, 1 to run process 1, or q to quit: 1
Process 1 in critical section: shared_resource = 2
Enter 0 to run process 0, 1 to run process 1, or q to quit: q
Executed Output:

Result:

Hence I have successfully completed the Deadlock and concurrency with semaphore with Petersons Algorithm

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

Implement a program to simulate the implementation of a simple file cache.

Aim: To implement a simple file cache simulation that stores file contents in memory, allowing quick access to
frequently used files without reading from disk each time
Description:
The file cache program maintains a cache of file contents to reduce the need for disk I/O operations. It allows
users to request files, which are then either loaded from the cache or read from disk if not cached. The cache
has a limited size, so it employs a policy (like Least Recently Used, LRU) to evict old files when the cache is full.
Program:
from collections import OrderedDict

class FileCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity

def get_file(self, filename: str) -> str:


if filename in self.cache:
# Move the accessed file to the end to show that it was recently used
self.cache.move_to_end(filename)
print(f"File '{filename}' retrieved from cache.")
else:
# Simulate reading the file from disk
content = self.read_file_from_disk(filename)
if len(self.cache) >= self.capacity:
# Remove the first item in the ordered dict (LRU policy)
removed_file = self.cache.popitem(last=False)
print(f"Cache is full. Removed the least recently used file: {removed_file[0]}")
self.cache[filename] = content
print(f"File '{filename}' loaded from disk into cache.")
return self.cache[filename]

def read_file_from_disk(self, filename: str) -> str:


# For simulation purposes, returning a string representing file content
return f"Contents of {filename}"

# Simulation
def main():
capacity = int(input("Enter cache capacity: "))
cache = FileCache(capacity)

while True:
filename = input("Enter filename to retrieve (or 'exit' to quit): ")
if filename.lower() == 'exit':
break
content = cache.get_file(filename)
print(f"File content: {content}\n")

if __name__ == "__main__":
main()
OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula
DATE: EXP NO: PAGE NO:

Sample Output:

Enter cache capacity: 2


Enter filename to retrieve (or 'exit' to quit): file1.txt
Executed Output:

Result:
Hence I have successfully completed the Implementation of a program to simulate the implementation of a
simple file cache.

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

DISK SCHEDULING ALGORITHMS


C-LOOK
Aim:
To implement the C-LOOK disk scheduling algorithm in Python, which is used to manage how disk read/write
requests are handled in an operating system.
Description:
The C-LOOK (Circular LOOK) algorithm is a variant of the LOOK disk scheduling algorithm. It works by first sorting
all the requests, then servicing the requests in one direction until it reaches the end of the list or disk, and then it
wraps around to the beginning of the list without moving back on the disk, effectively reducing seek time. The
head moves towards the end of the queue, processes the requests in that direction, and then jumps back to the
beginning of the queue without processing any requests in the opposite direction.
Program:
def clook(requests, head):
seek_sequence = []
total_seek_time = 0
requests = sorted(requests)
requests.append(head)

requests = [req for req in requests if req >= head]


if requests:
seek_sequence.extend(requests)
total_seek_time += abs(requests[-1] - head)

requests = [req for req in requests if req < head]


seek_sequence.extend(requests)
total_seek_time += abs(seek_sequence[0] - requests[-1])

return seek_sequence, total_seek_time

disk_size = int(input("Enter disk size: "))


requests = list(map(int, input("Enter disk requests separated by spaces: ").split()))
head = int(input("Enter initial head position: "))
OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula
DATE: EXP NO: PAGE NO:

sequence, total_seek_time = clook(requests, head)


print("C-LOOK Seek Sequence:", sequence)
print("Total Seek Time:", total_seek_time)
Sample output:
Enter disk size: 200
Enter disk requests separated by spaces: 82 170 43 140 24 16 190
Enter initial head position: 50
Executed output:

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

C-SCAN (Circular SCAN)

Aim:
To implement the C-SCAN (Circular SCAN) disk scheduling algorithm in Python, which manages how disk
read/write requests are handled in an operating system.
Description:
The C-SCAN (Circular SCAN) algorithm is a variant of the SCAN disk scheduling algorithm. The disk arm moves
towards the end of the disk, servicing requests along the way. Once it reaches the end, it immediately jumps to
the beginning of the disk without servicing any requests during the return. This process is then repeated in the
same direction.
Program:
def cscan(requests, head, disk_size):
seek_sequence = []
total_seek_time = 0
requests = sorted(requests)
requests.append(disk_size)
requests.append(0)

while requests and head < disk_size:


closest = min(requests, key=lambda x: abs(x - head))
seek_sequence.append(closest)
total_seek_time += abs(closest - head)
head = closest
requests.remove(closest)

if head != disk_size:
total_seek_time += (disk_size - head)
head = 0
seek_sequence.append(0)

return seek_sequence, total_seek_time

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

disk_size = int(input("Enter disk size: "))


requests = list(map(int, input("Enter disk requests separated by spaces: ").split()))
head = int(input("Enter initial head position: "))

sequence, total_seek_time = cscan(requests, head, disk_size)


print("C-SCAN Seek Sequence:", sequence)
print("Total Seek Time:", total_seek_time)
sample output:
Enter disk size: 200
Enter disk requests separated by spaces: 82 170 43 140 24 16 190
Enter initial head position: 50
Executed output:

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

FCFS (First-Come, First-Served)

Aim:
To implement the FCFS (First-Come, First-Served) disk scheduling algorithm in Python, which manages how disk
read/write requests are handled in an operating system.
Description:
The FCFS (First-Come, First-Served) disk scheduling algorithm is the simplest form of disk scheduling. The
requests are serviced in the order they arrive, without reordering. The algorithm moves the disk arm directly
from the current head position to the position of each request in the sequence they appear.
Program:
def fcfs(requests, head):
seek_sequence = []
total_seek_time = 0
seek_sequence.append(head)
for req in requests:
seek_sequence.append(req)
total_seek_time += abs(req - head)
head = req
return seek_sequence, total_seek_time

disk_size = int(input("Enter disk size: "))


requests = list(map(int, input("Enter disk requests separated by spaces: ").split()))
head = int(input("Enter initial head position: "))

sequence, total_seek_time = fcfs(requests, head)


print("FCFS Seek Sequence:", sequence)
print("Total Seek Time:", total_seek_time)

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

sample output:
Enter disk size: 200
Enter disk requests separated by spaces: 98 183 37 122 14 124 65 67
Enter initial head position: 53
Executed output:

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

LOOK disk scheduling algorithm


Aim:
To implement the LOOK disk scheduling algorithm in Python, which manages how disk read/write requests are
handled in an operating system.
Descrption:
The LOOK algorithm is a variant of the SCAN disk scheduling algorithm. Instead of moving the disk arm to the
end of the disk, the LOOK algorithm only goes as far as the last request in the current direction, then reverses. It
"looks" ahead to see if there are any more requests to be serviced in the current direction before reversing.
Program:
def look(requests, head, direction):
seek_sequence = []
total_seek_time = 0
requests = sorted(requests)

if direction == 'right':
requests = [req for req in requests if req >= head]
seek_sequence.extend(requests)
if requests:
total_seek_time += abs(requests[-1] - head)
seek_sequence.append(requests[-1])
requests = [req for req in requests if req < head]
seek_sequence.extend(requests)
total_seek_time += abs(requests[0] - requests[-1])

elif direction == 'left':


requests = [req for req in requests if req <= head]
seek_sequence.extend(reversed(requests))
if requests:
total_seek_time += abs(head - requests[0])
seek_sequence.append(requests[0])
requests = [req for req in requests if req > head]
seek_sequence.extend(requests)

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

total_seek_time += abs(requests[-1] - requests[0])

return seek_sequence, total_seek_time

disk_size = int(input("Enter disk size: "))


requests = list(map(int, input("Enter disk requests separated by spaces: ").split()))
head = int(input("Enter initial head position: "))
direction = input("Enter direction (right/left): ")

sequence, total_seek_time = look(requests, head, direction)


print("LOOK Seek Sequence:", sequence)
print("Total Seek Time:", total_seek_time)
expected output:
Enter disk size: 200
Enter disk requests separated by spaces: 98 183 37 122 14 124 65 67
Enter initial head position: 53
Enter direction (right/left): right
Executed ouput:

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

SCAN disk scheduling algorithm


Aim:
To implement the SCAN disk scheduling algorithm in Python, which manages how disk read/write requests are
handled in an operating system
Description:
The SCAN disk scheduling algorithm moves the disk arm in one direction (either right or left), servicing all
requests until it reaches the end of the disk or the last request in that direction. Once it reaches the end, it
reverses direction and services the remaining requests.
Program:
def scan(requests, head, disk_size, direction):
seek_sequence = []
total_seek_time = 0
requests = sorted(requests)
requests.append(disk_size)
requests.append(0)

if direction == 'right':
requests = [req for req in requests if req >= head]
seek_sequence.extend(requests)
total_seek_time += abs(requests[-1] - head)
seek_sequence.append(0)
requests = [req for req in requests if req < head]
seek_sequence.extend(requests)
total_seek_time += abs(0 - requests[0])

elif direction == 'left':


requests = [req for req in requests if req <= head]
seek_sequence.extend(reversed(requests))
total_seek_time += abs(head - requests[0])
seek_sequence.append(disk_size)
requests = [req for req in requests if req > head]
seek_sequence.extend(requests)

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

total_seek_time += abs(disk_size - requests[-1])

return seek_sequence, total_seek_time

disk_size = int(input("Enter disk size: "))


requests = list(map(int, input("Enter disk requests separated by spaces: ").split()))
head = int(input("Enter initial head position: "))
direction = input("Enter direction (right/left): ")

sequence, total_seek_time = scan(requests, head, disk_size, direction)


print("SCAN Seek Sequence:", sequence)
print("Total Seek Time:", total_seek_time)
Sample Output:
Enter disk size: 200
Enter disk requests separated by spaces: 98 183 37 122 14 124 65 67
Enter initial head position: 53
Enter direction (right/left): right
SCAN Seek Sequence: [65, 67, 98, 122, 124, 183, 200, 0, 14, 37]
Total Seek Time: 387
Executed Output:

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

SSTF (Shortest Seek Time First)

Aim:
To implement the SSTF (Shortest Seek Time First) disk scheduling algorithm in Python, which manages how disk
read/write requests are handled in an operating system.
Description:
The SSTF (Shortest Seek Time First) algorithm selects the request with the shortest seek time (i.e., the closest
request) from the current head position. It services this closest request first before selecting the next closest
request, thereby minimizing the seek time at each step.
Program:
def sstf(requests, head):
seek_sequence = []
total_seek_time = 0
requests = sorted(requests)
while requests:
closest = min(requests, key=lambda x: abs(x - head))
seek_sequence.append(closest)
total_seek_time += abs(closest - head)
head = closest
requests.remove(closest)
return seek_sequence, total_seek_time

disk_size = int(input("Enter disk size: "))


requests = list(map(int, input("Enter disk requests separated by spaces: ").split()))
head = int(input("Enter initial head position: "))

sequence, total_seek_time = sstf(requests, head)


print("SSTF Seek Sequence:", sequence)
print("Total Seek Time:", total_seek_time)

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

Sample Output:
Enter disk size: 200
Enter disk requests separated by spaces: 98 183 37 122 14 124 65 67
Enter initial head position: 53
SSTF Seek Sequence: [65, 67, 98, 122, 124, 183, 37, 14]
Total Seek Time: 390
Executed Output:

Result:
Hence I have successfully completed disk scheduling algorithms

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


DATE: EXP NO: PAGE NO:

EXPERIMENT :15

AIM:

write a collection of programs p1 p2 an p3 such that they execute sequentially with the same pid and each
program should involve any combination of these programs to achieve the required functionality for example
consider three programs twice, half, an square which accept only one integer as argument and does some
specific operations. These operations may be like 1. twice ten prints twenty and some number which is its pid 2.
half ten prints five and some number which is its pid 3. square ten prints hundred and some number which is its
pid now the users should be able to combine these programs in any combinations to achieve the desired result
for example input: twice,square,half,twice,half,ten output: [half[twice[half[square[twice 10]]]]]
DESCRIPTION:
To create a collection of programs (p1, p2, p3) that execute sequentially with the same PID and achieve the
required functionality, we can use Unix pipes to pass the output of one program as the input to the next. In this
example, we will create three programs: twice, half, and square, which accept a single integer as an argument
and perform specific operations.
Here are the steps to implement this:
1. Create the individual programs:
o twice: Multiplies the input by 2.
o half: Divides the input by 2.
o square: Squares the input.
2. Create a main script to combine these programs and execute them sequentially:
o The main script will parse the input string to determine the sequence of operations and apply
them in the specified order.
PROGRAM CODE:
twice.py

import sys

import os

def twice(n):

return n * 2
if name == " main ":
if len(sys.argv) != 2:
print("Usage: twice <number>")
sys.exit(1)
num = int(sys.argv[1])
result = twice(num)
print(f"{result} {os.getpid()}")
OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula
DATE: EXP NO: PAGE NO:

half.py
import sys
import os
def half(n):
return n // 2
if name == " main ":
if len(sys.argv) != 2:
print("Usage: half <number>")
sys.exit(1)
num = int(sys.argv[1])
result = half(num)
print(f"{result} {os.getpid()}")
square.py

import sys

import os

def square(n):
return n ** 2
if name == " main ":
if len(sys.argv) != 2:
print("Usage: square <number>")
sys.exit(1)
num = int(sys.argv[1])
result = square(num)
print(f"{result} {os.getpid()}")
main.py
import subprocess
import sys
def execute_programs(programs, num):
current_value = num
for program in programs:
process = subprocess.Popen(

OPERATING SYSTEMS LABORATORY JNTUA College Of Engineering (Autonomous) Pulivendula


Date: Exp No: Page no:

[sys.executable, program,
str(current_value)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
output, error =
process.communicate() if
process.returncode != 0:
print(f"Error in {program}: {error.decode().strip()}")
return
current_value, pid = map(int,
output.decode().strip().split()) print(f"After {program}:
{current_value} (PID: {pid})")
print(f"Final Result:
{current_value}") if name == "
main ":
if len(sys.argv) < 3:
print("Usage: main <program1,program2,...>
<number>") sys.exit(1)
program_sequence =
sys.argv[1].split(',') number =
int(sys.argv[2]) program_paths = {
'twice': './twice.py',
'half': './half.py',
'square': './square.py'
}

programs = [program_paths[prog] for prog in program_sequence]


execute_programs(programs, number)
EXPECTED OUTPUT:

After twice.py: 20 (PID: 12345)


After half.py: 10 (PID: 12346)
After square.py: 100 (PID: 12347)
Final Result: 100

Operating Systems Laboratory JNTUA College of Engineering (Autonomous) Pulivendula


Date: Exp No: Page no:

EXECUTED OUTPUT:

RESULT: The program has been successfully executed.

Operating Systems Laboratory JNTUA College of Engineering (Autonomous) Pulivendula

You might also like