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

OS Program

Program to implement operation system

Uploaded by

KESAVAN KD
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)
27 views

OS Program

Program to implement operation system

Uploaded by

KESAVAN KD
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/ 36

1 .

BASIC I/O PROGAMMING - PROCESS CREATION

from multiprocessing import Process


import os
def info(title):
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')
p=Process(target=f,args=('bob',))
p.start()
p.join()
print("child process:",p.name)
print("child process ID:",p.pid)
OUTPUT:

module name: __main__

parent process: 8224

process id: 7924

child process: Process-1

child process ID: 3424


2 . SHORTEST JOB FIRST ALGORITHM

n=int(input('Enter no of process:'))
bt=[0]*(n+1)
at=[0]*(n+1)
abt=[0]*(n+1)
for i in range(n):
abt[i]=int(input('Enter brust time process{}:'.format(i+1)))
at[i]=int(input('Enter the arrival time for process{}:'.format(i+1)))
bt[i]=[abt[i],at[i],i]
bt.pop(-1)
print(abt)
print(bt)
sumbt=0
i=[]
ll=[]
for i in range(0,sum(abt)):
l=[j for j in bt if j[1]<=i]
l.sort(key=lambda X:X[0])
bt[bt.index(l[0])][0]-=1
for k in bt:
if k[0]==0:
t=bt.pop(bt.index(k))
ll.append([k,i+1])
ct=[0]*(n+1)
tat=[0]*(n+1)
wt=[0]*(n+1)
for i in ll:
ct[i[0][2]]=i[1]
for i in range(len(ct)):
tat[i]=ct[i]-at[i]
wt[i]=tat[i]-abt[i]
ct.pop(-1)
wt.pop(-1)

tat.pop(-1)
abt.pop(-1)
print('PNO\ABt\tAt\tTAT\tWt')
for i in range(len(ct)):
print("{}\t{}\t{}\t{}\t{}\t{}\n".format(i+1,abt[i],at[i],ct[i],tat[i],wt[i]))
print('Averge waiting Timing=',sum(wt),len(wt))
print('Average Turnaround Time=',sum(tat)/len(tat))
OUTPUT:

Enter no of process:4
Enter brust time process1:8
Enter the arrival time for process1:0
Enter brust time process2:4
Enter the arrival time for process2:1
Enter brust time process3:9
Enter the arrival time for process3:2
Enter brust time process4:5
Enter the arrival time for process4:3
[8, 4, 9, 5, 0]
[[8, 0, 0], [4, 1, 1], [9, 2, 2], [5, 3, 3]]
PNO\ABt At TAT Wt
1 8 0 0 0 -8

2 4 1 0 -1 -5

3 9 2 0 -2 -11

4 5 3 0 -3 -8

Averge waiting Timing= -32 4


Average Turnaround Time= -1.5
3. FIRST COME FIRST SERVED ALGORITHM

def findWaitingTime(Processes,n,bt,wt):
wt[0]=0
for i in range(1,n):
wt[i]=bt[i-1]+wt[i-1]
def findTurnAroundTime(processes,n,bt,wt,tat):
for i in range(n):
tat[i]=bt[i]+wt[i]
def findavgTime(processes,n,bt):
wt=[0]*n
tat=[0]*n
total_wt=0
total_tat=0
findWaitingTime(processes,n,bt,wt)
findTurnAroundTime(processes,n,bt,wt,tat)
print("processes burst time"+"Waiting time"+"Turn around time")
for i in range(n):
total_wt=total_wt+wt[i]
total_tat=total=total_tat+tat[i]
print(""+str(i+1)+"\t\t"+ str(bt[i])+"\t"+str(wt[i])+"\t\t"+str(tat[i]))
print("Average waiting time="+str(total_wt/n))
print("Average turn around time="+str(total_tat/n))
if __name__=="__main__":
processes=[1,2,3]
n=len(processes)
burst_time=[24,3,3]

findavgTime(processes,n,burst_time)
OUTPUT:

processes burst timeWaiting timeTurn around time


1 24 0 24
2 3 24 27
3 3 27 30
Average waiting time=17.0
Average turn around time=27.0
4 (a). ROUND ROBIN SCHEDULING ALGORITHM

def findWaitingTime(processes,n,bt,wt,quantum):
rem_bt = [0] * n
for i in range (n):
rem_bt[i] = bt[i]
t=0
while(1):
done=True
for i in range (n):
if(rem_bt[i]>0):
done=False
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==True):
break
def findTurnAroundTime(processes,n,bt,wt,tat):
for i in range(n):
tat[i]=bt[i]+wt[i]
def findavgTime(processes,n,bt,quantum):
wt=[0]*n
tat=[0]*n
findWaitingTime(processes,n,bt,wt,quantum)
findTurnAroundTime(processes,n,bt,wt,tat)
print("Processes \t Burst time \t Waiting time \t Turn around time")
total_wt=0
total_tat=0
for i in range(n):
total_wt=total_wt+wt[i]
total_tat=total_tat+tat[i]
print("",i+1,"\t\t",bt[i],"\t\t",wt[i],"\t\t",tat[i])
print("\nAverage Waiting time=%.5f"%(total_wt/n))
print("Avarage turn around time=%.5f"%(total_tat/n))
if __name__=="__main__":
proc=[1,2,3]
n=3
burst_time=[10,5,8]
burst_time=[24,3,3]
quantum=4;
findavgTime(proc,n,burst_time,quantum)
OUTPUT:

Processes Burst time Waiting time Turn around time


1 24 6 30
2 3 27 30
3 3 27 30

Average Waiting time=20.00000


Avarage turn around time=30.00000
4 (b). PRIORITY SCHEDULING ALGORITHM

def findWaitingTime(processes,n,wt):
wt[0]=0
for i in range(1,n):
wt[i]=processes[i-1][1]+wt[i-1]
def findTurnAroundTime(processes,n,wt,tat):
for i in range(1,n):
tat[i]=processes[i][1]+wt[i]
def findavgTime(processes,n):
wt=[0]*n
tat=[0]*n
findWaitingTime(processes,n,wt)
findTurnAroundTime(processes,n,wt,tat)
print("\nprocesses \tBurst Time \tWaiting","Time \t Turn-Around Time")
total_wt=0
total_tat=0
for i in range(n):
total_wt=total_wt+wt[i]
total_tat=total_tat+tat[i]
print("",processes[i] [0],"\t\t",processes[i][1],"\t\t",wt[i],"\t\t",tat[i])
print("\nAverage Waiting time = %.5f"%(total_wt/n))
print("Average turn around time = ",(total_tat/n))
def priorityScheduling(proc,n):
proc=sorted(proc, key=lambda proc:proc[2],reverse=True);
print("Order in which process gets executed")
for i in proc:
print(i[0],end=" ")
findavgTime(proc,n)
if __name__=="__main__":
proc=[[1,10,1],[2,5,0],[3,8,1]]
n=3
print("Priority Scheduling Algorithm")
priorityScheduling(proc,n)
OUTPUT:

Priority Scheduling Algorithm


Order in which process gets executed
132
processes Burst Time Waiting Time Turn-Around Time
1 10 0 0
3 8 10 18
2 5 18 23

Average Waiting time = 9.33333


Average turn around time = 13.666666666666666
5. IMPLEMENT READER / WRITER PROBLEM USING SEMAPHORE

import threading
import time
class ReaderWriterProblem():
def __init__(self):
self.mutex=threading.Semaphore()
self.wrt=threading.Semaphore()
self.r_c=0
def reader(self):
while True:
self.mutex.acquire()
self.r_c+=1
if self.r_c==1:
self.wrt.acquire()
self.mutex.release()
print(f"\nReader {self.r_c} is reading")
self.mutex.acquire()
self.r_c-=1
if self.r_c==0:
self.wrt.release()
self.mutex.release()
time.sleep(3)
def writer(self):
while True:
self.wrt.acquire()
print("Writing data....")
print("-"*20)
self.wrt.release()
time.sleep(3)
def main(self):
t1=threading.Thread(target=self.reader)
t1.start()
t2=threading.Thread(target=self.writer)
t2.start()
t3=threading.Thread(target=self.reader)
t3.start()
t4=threading.Thread(target=self.reader)
t4.start()
t6=threading.Thread(target=self.writer)
t6.start()
t5=threading.Thread(target=self.reader)
t5.start()
if __name__=="__main__":
c=ReaderWriterProblem()
c.main()
OUTPUT:

Reader 1 is reading

Reader 3 is reading

Reader 2 is reading

Reader 4 is reading

Writing data....

--------------------

Writing data....

--------------------

Reader 1 is reading

Reader 2 is reading

Reader 3 is reading

Reader 4 is reading

Writing data....

--------------------

Writing data....
6. IMPLEMENT BANKER’S ALGORITHM FOR DEADLOCK
AVOIDANCE

P=5
R=3
def calculateNeed(need, maxm, allot):
for i in range(P):
for j in range(R):
need[i][j] = maxm[i][j] - allot[i][j]
def isSafe(processes, avail, maxm, allot):
need = []
for i in range(P):
l = []
for j in range(R):
l.append(0)
need.append(l)
calculateNeed(need, maxm, allot)
finish = [0] * P
safeSeq = [0] * P
work = [0] * R
for i in range(R):
work[i] = avail[i]
count = 0
while (count < P):
found = False
for p in range(P):
if (finish[p] == 0):
for j in range(R):
if (need[p][j] > work[j]):
break
if (j == R - 1):
for k in range(R):
work[k] += allot[p][k]
safeSeq[count] = p
count += 1
finish[p] = 1
found = True
if (found == False):
print("System is not in safe state")
return False
print("System is in safe state.",
"\nSafe sequence is: ", end = " ")
print(*safeSeq)
return True
if __name__ =="__main__":
processes = [0, 1, 2, 3, 4]
avail = [3, 3, 2]
maxm = [[7, 5, 3], [3, 2, 2],
[9, 0, 2], [2, 2, 2],
[4, 3, 3]]
allot = [[0, 1, 0], [2, 0, 0],
[3, 0, 2], [2, 1, 1],
[0, 0, 2]]
isSafe(processes, avail, maxm, allot)
OUTPUT:

System is in safe state.

Safe sequence is: 1 3 4 0 2


7. FIRST IN FIRST OUT ALGORITHM

from queue import Queue


def pageFaults(pages ,n,capacity):
s=set()
indexes=Queue()
page_faults=0
for i in range(n):
if(len(s) < capacity):
if(pages[i]not in s):
s.add(pages[i])
page_faults+=1
indexes.put(pages[i])
else:
if(pages[i]not in s):
val=indexes.queue[0]
indexes.get()
s.remove(val)
s.add(pages[i])
indexes.put(pages[i])
page_faults+=1
print(s,end=" ")
print("page Fault count",page_faults)
return page_faults
if __name__=="__main__":
pages=[3,2,1,0,3,2,4,3,2,1,0,4]
n=len(pages)
capacity=3
print("Total page Fault count :",pageFaults(pages,n,capacity))
OUTPUT:

{3} page Fault count 1

{2, 3} page Fault count 2

{1, 2, 3} page Fault count 3

{0, 1, 2} page Fault count 4

{0, 1, 3} page Fault count 5

{0, 2, 3} page Fault count 6

{2, 3, 4} page Fault count 7

{2, 3, 4} page Fault count 7

{2, 3, 4} page Fault count 7

{1, 2, 4} page Fault count 8

{0, 1, 4} page Fault count 9

{0, 1, 4} page Fault count 9

Total page Fault count : 9


8. LEAST RECENTLY USED ALGORITHM

capacity=3
processList=[0,1,2,0,3,0,4,2,3,0,3,2]
s=[]
pageFaults=0
for i in processList:
if i not in s:
if(len(s)==capacity):
s.remove(s[0])
s.append(i)
else:
s.append(i)
pageFaults+=1
else:
s.remove(i)
s.append(i)
print(s,end=" ")
print("page fault count",pageFaults)
print("Total pageFaults :",pageFaults)
OUTPUT:

[0] page fault count 1

[0, 1] page fault count 2

[0, 1, 2] page fault count 3

[1, 2, 0] page fault count 3

[2, 0, 3] page fault count 4

[2, 3, 0] page fault count 4

[3, 0, 4] page fault count 5

[0, 4, 2] page fault count 6

[4, 2, 3] page fault count 7

[2, 3, 0] page fault count 8

[2, 0, 3] page fault count 8

[0, 3, 2] page fault count 8

Total pageFaults : 8
9 (a). IMPLEMENT FIRST FIT ALGORITHM FOR MEMORY
MANAGEMENT
def FirstFit(block_size,blocks,process_size,proccesses):
allocate=[-1]*proccesses
occupied=[False]*blocks
for i in range(proccesses):
for j in range(blocks):
if not occupied[j] and (block_size[j]>=process_size[i]):
allocate[i]=j
occupied[j]=True
break
print("Process No \t\tProcess Size \tBlock No")
for i in range(proccesses):
print(str(i+1)+"\t\t\t"+str(process_size[i])+"\t\t",end="")
if allocate[i] !=-1:
print(allocate[i]+1)
else:
print("not allocated")
block_size=[100,50,30,120,35]
process_size=[20,60,70,40]
m=len(block_size)
n=len(process_size)

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
9(b). IMPLEMENT BEST FIT ALGORITHM FOR MEMORY
MANAGEMENT

def bestFit(blocksize,m,processsize,n):
allocation=[-1]*n
for i in range(n):
bestIdx=-1
for j in range(m):
if blocksize[j]>=processsize[i]:
if bestIdx==-1:
bestIdx=j
elif blocksize[bestIdx]>blocksize[j]:
bestIdx=j
if bestIdx !=-1:
allocation[i]=bestIdx
blocksize[bestIdx]-=processsize[i]
print("Process No \t\tProcess Size \t Block No")
for i in range(n):
print(str(i+1)+"\t\t\t"+str(processsize[i])+"\t\t",end=" ")
if allocation[i] !=-1:
print(allocation[i]+1)
else:
print("not allocated")
if __name__=='__main__':
blocksize=[100,500,200,300,600]
processsize=[212,417,112,426]
m=len(blocksize)
n=len(processsize)
bestFit(blocksize,m,processsize,n)
OUTPUT:

Process No Process Size Block No

1 212 4

2 417 2

3 112 3

4 426 5
9(C). IMPLEMENT WORST FIT ALGORITHM FOR MEMORY
MANAGEMENT

def worstFit(blockSize,m,processSize,n):
allocation = [-1] * n
for i in range(n):
wstIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if wstIdx == -1:
wstIdx = j
elif blockSize[wstIdx] < blockSize[j]:
wstIdx = j
if wstIdx != -1:
allocation[i] = wstIdx
blockSize[wstIdx] -= processSize[i]
print("Process No \t Process Size \t\t Block No")
for i in range(n):
print (i + 1, "\t\t ", processSize[i],"\t\t\t", end = " ")
if allocation[i] != -1:
print(allocation[i] + 1)
else:
print("Not Allocation")
if __name__=='__main__':
blockSize = [100,500,200,300,600]
processSize = [212,417,112,426]
m = len(blockSize)
n = len(processSize)
worstFit(blockSize,m,processSize,n)
OUTPUT:

Process No Process Size Block No

1 212 5

2 417 2

3 112 5

4 426 Not Allocation


10. INTER-PROCES COMMUNICATION WITH SHARED MEMORY

from multiprocessing import Process,Value, Array

def f(n,a):

n.value=3.1415927

for i in range(len(a)):

a[i]=-a[i]

if __name__=='__main__':

num=Value('d',0.0)

arr=Array('i',range(10))

arr1=Array('i',range(1,20,2))

print("\t\tIPC using shared memory")

p1=Process(target=f,args=(num,arr))

p1.start()

p1.join()

p2=Process(target=f,args=(num,arr1))

p2.start()

p2.join()

print(num.value)

print(arr[:])

print(arr1[:])
OUTPUT:

IPC using shared memory

3.1415927

[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

[-1, -3, -5, -7, -9, -11, -13, -15, -17, -19]

You might also like