extra programs of os
extra programs of os
# 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)
# Critical section
shared_resource += 1
print("Process 0 in critical section: shared_resource =", shared_resource)
# Exit section
flag[0] = False
global shared_resource
flag[1] = True
turn = 0
# Critical section
shared_resource += 1
print("Process 1 in critical section: shared_resource =", shared_resource)
# Exit section
flag[1] = False
if _name_ == "_main_":
main()
Sample Output:
Result:
Hence I have successfully completed the Deadlock and concurrency with semaphore with Petersons Algorithm
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
# 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:
Result:
Hence I have successfully completed the Implementation of a program to simulate the implementation of a
simple file cache.
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)
if head != disk_size:
total_seek_time += (disk_size - head)
head = 0
seek_sequence.append(0)
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
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:
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])
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])
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
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
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(
[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'
}
EXECUTED OUTPUT: