17mi550 Adv Os Lab File
17mi550 Adv Os Lab File
Lab #1
import random
from prettytable import PrettyTable
2. x = PrettyTable()
3. x.field_names = ["Process", "Time of Arrival", "Time processed", "Burst Time", "Waiting Ti
me"]
4.
5. def comp(A):
6. return A.A
7.
8. class Process:
9. def __init__(self, arrival_time, burst_time, waiting_time=0):
10. self.A = arrival_time
11. self.B = burst_time
12. self.W = waiting_time
13.
14. def setWaitingTime(self, time):
15. self.W = time
16. def __str__(self):
17. return "[A:{} B:{} W:{}]".format(self.A, self.B, self.W)
18.
19. def fcfs(P, n):
20. x.add_row(["P0", P[0].A, P[0].A, P[0].B, 0])
21. for i in range(1,n):
22. x.add_row([
23. "P{}".format(i),
24. P[i].A,
25. P[i-1].W + P[i-1].B,
26. P[i].B,
27. P[i-1].W + P[i-1].B - P[i].A if((P[i-1].W + P[i-1].B - P[i].A) >= 0) else 0
28. ])
29. P[i].setWaitingTime(P[i-1].W + P[i-1].B - P[i].A if((P[i-1].W + P[i-
1].B - P[i].A) >= 0) else 0)
30. print(x.get_string())
31. sum = 0
32. for p in P:
33. sum += p.W
34. print("Total Waiting Time:{}".format(sum))
35.
36. if __name__=="__main__":
37. processes = []
38. n = random.randint(10, 100)
39. for i in range(n):
40. P = Process(random.randint(0, 100), random.randint(0, 100))
41. processes.append(P)
42. processes.sort(key=comp)
43. fcfs(processes, n)
44.
Output:
b. Round Robin
import random
from prettytable import PrettyTable
x = PrettyTable()
x.field_names = ["Process", "Time of Arrival", "Time processed", "Burst Time", "Waiting Time"]
def comp(A):
return A.A
class Process:
def __init__(self, arrival_time, burst_time, waiting_time=0):
self.name = ""
self.A = arrival_time
self.B = burst_time
self.W = waiting_time
def setBurstTime(self, time):
self.B = time
def setWaitingTime(self, time):
self.W = time
def __str__(self):
return "[A:{} B:{} W:{}]".format(self.A, self.B, self.W)
print(x.get_string())
if __name__=="__main__":
processes = []
n = random.randint(1, 10)
print("Number of processes: {}".format(n))
for i in range(n):
P = Process(random.randint(1, 50), random.randint(1, 20))
processes.append(P)
processes.sort(key=comp)
for i in range(len(processes)):
processes[i].name = "P{}".format(i)
T = random.randint(1,10)
print("Round Robin Time = {}".format(T))
round_robin(processes, n, T)
Output:
import random
from prettytable import PrettyTable
x = PrettyTable()
x.field_names = ["Process Time", "Burst Time"]
if __name__=="__main__":
process_queue = []
total_wtime = 0
n = random.randint(1,20)
print('Enter the total no of processes: {}'.format(n))
for i in range(n):
process_queue.append([])
process_queue[i].append("pro_"+str(i))
process_queue[i].append(random.randint(1,20))
process_queue.sort(key = lambda process_queue:process_queue[1])
for i in process_queue[:n-1]:
total_wtime+=total_wtime+i[1]
for i in range(n):
x.add_row([process_queue[i][0],process_queue[i][1]])
print(x.get_string())
Output
d. Priority
import random
from prettytable import PrettyTable
x = PrettyTable()
x.field_names = ["Process Time", "Burst Time", "Priority"]
if __name__=="__main__":
process_queue = []
total_wtime = 0
n = random.randint(1, 10)
print('Enter the total no of processes: {}'.format(n))
pr_list=list(range(0,n))
for i in range(n):
process_queue.append([])
process_queue[i].append("pro_"+str(i))
process_queue[i].append(int(random.randint(1,20)))
bb=random.randint(0,len(pr_list)-1)
process_queue[i].append(pr_list[bb])
pr_list.pop(bb)
process_queue.sort(key = lambda process_queue:process_queue[2])
total_wtime = 0
for i in process_queue[:n-1]:
total_wtime+=total_wtime+i[1]
for i in range(n):
x.add_row([process_queue[i][0],process_queue[i][1],process_queue[i][2]])
print(x.get_string())
Output
LAB #2
Aim: Simulate following page replacement algorithms:
a) FIFO
import random
def fifo(A, n):
B = []
i = 0
res = 0
for a in A:
if(len(B) < n):
B.append(a)
print("Miss: new page frame:", B)
res += 1
continue
if a in B:
print("Hit in ", B)
else:
B[i] = a
i = (i+1)%n
res += 1
print("Miss: new page frame: ", B)
return res
if __name__ == "__main__":
total = random.randint(0, 20)
print("No. of pages: ", total)
print("Enter pages space seprated")
A = []
for i in range(total):
c = random.randint(0, 10)
A.append(c)
print(c, end=" ")
print()
n = random.randint(0, 7)
print("Enter page frame size:", n)
print("No. of misses:", fifo(A, n))
Output:
import random
def lru():
n = random.randint(1, 7)
print("Enter the frame size:", n)
f,st,fault,pf = [],[],0,'No'
total = random.randint(0, 20)
s = []
print("Enter the reference string:",end=" ")
for i in range(total):
c = random.randint(0, 10)
s.append(c)
print(c, end=" ")
print()
print("\nStrig|Frame →\t",end='')
for i in range(n):
print(i,end=' ')
print("Fault\n ↓\n")
for i in s:
if i not in f:
if len(f)<n:
f.append(i)
st.append(len(f)-1)
else:
ind = st.pop(0)
f[ind] = i
st.append(ind)
pf = 'Yes'
fault += 1
else:
st.append(st.pop(st.index(f.index(i))))
pf = 'No'
print(" %d\t\t"%i,end='')
for x in f:
print(x,end=' ')
for x in range(n-len(f)):
print(' ',end=' ')
print(" %s"%pf)
print("\nTotal Requests: %d\nTotal Page Faults: %d\nFault Rate: %0.2f%%"%(len(s),fault,(fa
ult/len(s))*100))
if __name__ == "__main__":
lru()
Output:
Lab #3
Aim: Implement a distributed file server using sockets on Linux. The server creates a thread per client. In
the first message, a client sends a file name to the server and asks for the length of the file. The
client caches the files locally. Use any cache coherence technique. A file is transferred to the client
block by block.
Receive.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#ifndef TRANSFER_FILE_TRANSFER_H
#define TRANSFER_FILE_TRANSFER_H
#endif
char addr[INET_ADDRSTRLEN];
printf("Start receive file: %s from %s\n", filename, inet_ntop(AF_INET, &clientaddr.sin_ad
dr, addr, INET_ADDRSTRLEN));
writefile(connfd, fp);
printf("Receive Success, NumBytes = %ld\n", total);
fclose(fp);
close(connfd);
return 0;
}
void writefile(int sockfd, FILE *fp)
{
ssize_t n;
char buff[MAX_LINE] = {0};
while ((n = recv(sockfd, buff, MAX_LINE, 0)) > 0)
{
total+=n;
if (n == -1)
{
perror("Receive File Error");
exit(1);
}
Send_file.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#ifndef TRANSFER_FILE_TRANSFER_H
#define TRANSFER_FILE_TRANSFER_H
#endif
sendfile(fp, sockfd);
//puts("Send Success");
printf("Send Success, NumBytes = %ld\n", total);
fclose(fp);
close(sockfd);
return 0;
}
Output:
Lab #4
Aim: Implement concurrent echo client-server application. (Write a server (TCP) C Program that opens a
listening socket and waits to serve client. Write a client (TCP) C++ Program that connects with
the server program knowing IP address and port number. Get the input string from console on
client and send it to server, server echoes back that string to client.)
Server.cpp
Client.cpp
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
Output:
Lab #5
Aim: Implement Cristian’s algorithm.
Server.py
import socket
from datetime import datetime, time
from time import sleep
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host=socket.gethostname()
port=9999
serversocket.bind(("127.0.0.1",port))
serversocket.listen(5)
while True:
print("In")
clientsocket,addr=serversocket.accept() # get the client address
print("Got a connection from %s" % str(addr))
currentTime=datetime.now()
clientsocket.send(str(currentTime).encode('utf-8'))
Client.py
import socket
from datetime import datetime, time
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port=9999
time1=datetime.now()
s.connect(("127.0.0.1", port))
tm=s.recv(1024).decode('utf-8')
time2=datetime.now()
s.close()
t1=time1.second*1000000+time1.microsecond
t2=time2.second*1000000+time2.microsecond
diff=(t2-t1)/2
newMicro = serverTime.microsecond+diff
Output:
Lab #6
Aim: Simulate the functioning of Lamport’s Logical Clock in ‘C++’.
#include<iostream>
#define SIZE 10
using namespace std;
class nodeProcesses {
public:
int data[SIZE];
nodeProcesses *next;
nodeProcesses() {
for(int p=0; p<SIZE; p++) {
data[p] = 0;
}
next = NULL;
}
int main() {
int n, events, sent, receive, sentE, recE, commLines = 0;
nodeProcesses *temp;
nodeProcesses *proc[SIZE]; //array of processes
cout<<"Enter no. of processes: ";
cin>>n;
int vector[n] = {0}; //representation of data
for(int i = 0; i < n; i++) { //number of processes
for(int v = 0; v < n; v++) {
vector[v] = 0;
}
cout<<temp1->data[n-1];
cout<<")";
temp1 = temp1->next;
}
cout<<endl;
}
return 0;
}
Output: