0% found this document useful (0 votes)
63 views24 pages

17mi550 Adv Os Lab File

This document contains the code for a lab experiment on distributed file systems and caching. The experiment implements a distributed file server using sockets on Linux. The server creates a thread per client. Clients first send a file name to the server and receive the file length. Files are then transferred from the server to clients block by block. Caching is used at the client side with some cache coherence technique. The code defines constants and functions for file transfer between client and server sockets.

Uploaded by

Namisha Goyal
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)
63 views24 pages

17mi550 Adv Os Lab File

This document contains the code for a lab experiment on distributed file systems and caching. The experiment implements a distributed file server using sockets on Linux. The server creates a thread per client. Clients first send a file name to the server and receive the file length. Files are then transferred from the server to clients block by block. Caching is used at the client side with some cache coherence technique. The code defines constants and functions for file transfer between client and server sockets.

Uploaded by

Namisha Goyal
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/ 24

National Institute of Technology Hamirpur

Department of Computer Science and Engineering


Aug – Dec 2020

Subject Name: Subject Code:

Advanced Operating Systems Lab CSD-416

Branch: Year/ Semester:

Computer Science & Engineering 4th / 7th


Dual Degree

Submitted By: Submitted To:

Namisha Goyal Dr. Siddharth Chauhan


17MI550
Advanced Operating System Lab
Lab Practicals
Submitted by:
Namisha Goyal
17MI550
CSE Dual 4th year

Lab #1

Aim: Simulate the following CPU scheduling algorithms.


a. First Come First Serve

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)

def round_robin(P, n, T):


queue = []
timer = 0
j = 0
i=0
while(j < n):
timer = P[j].A
queue.append(P[j])
j+=1
while(i<len(queue)):
timer += T
if(i==0):
x.add_row([
queue[i].name,
queue[i].A,
queue[i].A,
queue[i].B,
0
])
else:
x.add_row([
queue[i].name,
queue[i].A,
queue[i-1].A + queue[i-1].W + min(queue[i-1].B, T),
queue[i].B,
queue[i-1].A + queue[i-1].W + min(queue[i-
1].B, T) - queue[i].A if((queue[i-1].A + queue[i-1].W + min(queue[i-
1].B, T) - queue[i].A) > 0) else 0
])
queue[i].setWaitingTime(queue[i-1].A + queue[i-1].W + min(queue[i-
1].B, T) - queue[i].A if((queue[i-1].A + queue[i-1].W + min(queue[i-
1].B, T) - queue[i].A) > 0) else 0)
while(j < n and P[j].A <= timer):
queue.append(P[j])
j += 1
if(queue[i].B > T):
# print("Before", queue[i].B)
queue[i].setBurstTime(queue[i].B - T)
# print("after", queue[i].B)
queue.append(queue[i])
# print(queue[i].name, timer, queue[i].B)
i+=1
j+=1

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:

c. Shortest Job First

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())

print('Total waiting time: ',total_wtime)


print('Average waiting time: ',(total_wtime/n))

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:

(b) Least Recently Used

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

#define MAX_LINE 4096


#define LINSTENPORT 7788
#define SERVERPORT 8877
#define BUFFSIZE 4096

#endif

void writefile(int sockfd, FILE *fp);


ssize_t total=0;
int main(int argc, char *argv[])
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
perror("Can't allocate sockfd");
exit(1);
}

struct sockaddr_in clientaddr, serveraddr;


memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(SERVERPORT);

if (bind(sockfd, (const struct sockaddr *) &serveraddr, sizeof(serveraddr)) == -1)


{
perror("Bind Error");
exit(1);
}

if (listen(sockfd, LINSTENPORT) == -1)


{
perror("Listen Error");
exit(1);
}

socklen_t addrlen = sizeof(clientaddr);


int connfd = accept(sockfd, (struct sockaddr *) &clientaddr, &addrlen);
if (connfd == -1)
{
perror("Connect Error");
exit(1);
}
close(sockfd);

char filename[BUFFSIZE] = {0};


if (recv(connfd, filename, BUFFSIZE, 0) == -1)
{
perror("Can't receive filename");
exit(1);
}

FILE *fp = fopen(filename, "wb");


if (fp == NULL)
{
perror("Can't open file");
exit(1);
}

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);
}

if (fwrite(buff, sizeof(char), n, fp) != n)


{
perror("Write File Error");
exit(1);
}
memset(buff, 0, MAX_LINE);
}
}

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

#define MAX_LINE 4096


#define LINSTENPORT 7788
#define SERVERPORT 8877
#define BUFFSIZE 4096

#endif

void sendfile(FILE *fp, int sockfd);


ssize_t total=0;
int main(int argc, char* argv[])
{
if (argc != 3)
{
perror("usage:send_file filepath <IPaddress>");
exit(1);
}

int sockfd = socket(AF_INET, SOCK_STREAM, 0);


if (sockfd < 0)
{
perror("Can't allocate sockfd");
exit(1);
}

struct sockaddr_in serveraddr;


memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(SERVERPORT);
if (inet_pton(AF_INET, argv[2], &serveraddr.sin_addr) < 0)
{
perror("IPaddress Convert Error");
exit(1);
}

if (connect(sockfd, (const struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0)


{
perror("Connect Error");
exit(1);
}

char *filename = basename(argv[1]);


if (filename == NULL)
{
perror("Can't get filename");
exit(1);
}

char buff[BUFFSIZE] = {0};


strncpy(buff, filename, strlen(filename));
if (send(sockfd, buff, BUFFSIZE, 0) == -1)
{
perror("Can't send filename");
exit(1);
}
FILE *fp = fopen(argv[1], "rb");
if (fp == NULL)
{
perror("Can't open file");
exit(1);
}

sendfile(fp, sockfd);
//puts("Send Success");
printf("Send Success, NumBytes = %ld\n", total);
fclose(fp);
close(sockfd);
return 0;
}

void sendfile(FILE *fp, int sockfd)


{
int n;
char sendline[MAX_LINE] = {0};
while ((n = fread(sendline, sizeof(char), MAX_LINE, fp)) > 0)
{
total+=n;
if (n != MAX_LINE && ferror(fp))
{
perror("Read File Error");
exit(1);
}

if (send(sockfd, sendline, n, 0) == -1)


{
perror("Can't send file");
exit(1);
}
memset(sendline, 0, MAX_LINE);
}
}

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

// Server side C/C++ program to demonstrate Socket programming


#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char hello[1024];

// Creating socket file descriptor


if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}

// Forcefully attaching socket to the port 8080


if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );

// Forcefully attaching socket to the port 8080


if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
valread = read( new_socket , buffer, 1024);
printf("Message received from client: %s\n",buffer);
printf("Sending message again to the client.\n");
send(new_socket , buffer , strlen(buffer) , 0 );
printf("Message sent to client\n");
return 0;
}

Client.cpp

// Client side C/C++ program to demonstrate Socket programming


#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8080

int main(int argc, char const *argv[])


{
int sock = 0, valread;
struct sockaddr_in serv_addr;
char hello[1024];
printf("Enter your message: ");
scanf("%s", hello);
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}

serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);

// Convert IPv4 and IPv6 addresses from text to binary form


if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}

if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)


{
printf("\nConnection Failed \n");
return -1;
}
send(sock , hello , strlen(hello) , 0 );
printf("Message sent to the server.\n");
valread = read( sock , buffer, 1024);
printf("Message Received from server: %s\n",buffer );
return 0;
}

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()

# hang-up for 2 seconds.. done for processing delay


sleep(2)

clientsocket.send(str(currentTime).encode('utf-8'))

# terminate client connection


clientsocket.close()

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()

serverTime=datetime.strptime(tm, "%Y-%m-%d %H:%M:%S.%f")

s.close()

print("The time got from the server is: \n")


print("Hour: %d \n" % serverTime.hour)
print("Minute: %d \n" % serverTime.minute)
print("Second: %d \n" % serverTime.second)
print("Microsecond: %d \n" %serverTime.microsecond)

t1=time1.second*1000000+time1.microsecond
t2=time2.second*1000000+time2.microsecond
diff=(t2-t1)/2

newMicro = serverTime.microsecond+diff

print("Applying Cristian`s algorithm the actual time is: \n")


print("Hour: %d \n" % serverTime.hour)
print("Minute: %d \n" % serverTime.minute)
print("Second: %d \n" % serverTime.second)
print("Microsecond: %d \n" % newMicro)

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;
}

nodeProcesses(int v[], int n1) {


for(int s = 0; s < n1; s++) {
data[s] = v[s];
}
next = NULL;
}

friend class process;


}*start=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<<"Enter no. of events in process "<<i+1<<": ";


cin>>events;

for(int j = 1; j <= events; j++) {


vector[i] = j;
nodeProcesses *newnode = new nodeProcesses(vector,n);
if(start == NULL) {
start = newnode;
temp = start;
} else {
temp->next = newnode;
temp = temp->next;
}
}
proc[i] = start;
start = NULL;
}
cout<<"\nEnter the number of communication lines: ";
cin>>commLines;
nodeProcesses *tempS, *tempR;

for(int i = 0; i < commLines; i++) {


cout<<"\nEnter the sending process: ";
cin>>sent;
cout<<"\nEnter the receiving process: ";
cin>>receive;
cout<<"\nEnter the sending event number: ";
cin>>sentE;
cout<<"\nEnter the receiving event number: ";
cin>>recE;

tempS = proc[sent - 1];


tempR = proc[receive - 1];

for(int j = 1; j < sentE; j++)


tempS = tempS->next;

for(int j = 1; j < recE; j++)


tempR = tempR->next;

for(int j = 0; j < n; j++) {


tempR->data[j] = (tempR->data[j] < tempS->data[j]) ? tempS->data[j] : tempR-
>data[j];
}
}

cout<<"\nThe resulting vectors are:\n\n";


for(int k = 0; k < n; k++) {
cout<<"Process "<<k + 1<<": ";
nodeProcesses *temp1 = proc[k];
while(temp1) {
cout<<"(";
for(int f = 0; f < n - 1; f++)
cout<<temp1->data[f]<<",";

cout<<temp1->data[n-1];
cout<<")";
temp1 = temp1->next;
}
cout<<endl;
}

return 0;
}

Output:

You might also like