0% found this document useful (0 votes)
28 views48 pages

Os CN

Uploaded by

Shreyash Badole
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)
28 views48 pages

Os CN

Uploaded by

Shreyash Badole
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/ 48

Department Of Computer

Applications,
National Institute of Technology, Kurukshetra
Haryana, India

OS and CN lab (MCA 213)

Lab manual

Submitted By: Submitted to:


Name: Shreyash Mrs. Smruti ma’am
Roll No.: 523110056
Group: G4
Sem: 3

1
Index of Experiments
Teache
Sno. Experiment Page
r Sign

Implement CPU scheduling schemes: FCFS, SJF, SRTF, Priority, Round 4


1
Robin, Multi-Level Queue and find out avg. turn-around time, avg. waiting
time, response time, throughput
Implement file storage allocation techniques: Contiguous (using array), 18
2
Linked–list allocation (using linked list) and indirect allocation (indexing)

Implement File Directories: Single Level, Two Level, Tree Level, Acyclic 27
3 Graph Directory

Implement Disk Scheduling: FCFS, SSTF, SCAN, Circular SCAN, Look 32


4
and Circular Look

Implement different Network Topologies. Locating different interfaces, 44


5
routers and switches. Studying different pools of IP addresses.

Learn and observe the usage of different networking commands e.g. 48


6
PING, TRACEROUTE. Learning remote login using telnet session.
Measuring typical average delays between different locations of the
network.

2
3
1. Implement CPU scheduling schemes: FCFS, SJF, SRTF, Priority, Round
Robin, Multi-Level Queue and find out avg. turn-around time, avg. waiting
time, response time, throughput.

Solution:

FCFS scheduling :
import java.util.Scanner;

public class FCFS {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter number of processes: ");

int numP = scanner.nextInt();

int[] arrivalTimes = new int[numP];

int[] burstTimes = new int[numP];

int[] completionTimes = new int[numP];

int[] turnAroundTimes = new int[numP];

int[] waitingTimes = new int[numP];

int[] responseTimes = new int[numP];

int totalTat = 0;

int totalWt = 0;

System.out.println("Enter arrival times:");

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

arrivalTimes[i] = scanner.nextInt();

4
System.out.println("Enter burst times:");

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

burstTimes[i] = scanner.nextInt();

int currentTime = 0;

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

if (currentTime < arrivalTimes[i]) {

currentTime = arrivalTimes[i];

completionTimes[i] = currentTime + burstTimes[i];

currentTime = completionTimes[i];

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

turnAroundTimes[i] = completionTimes[i] - arrivalTimes[i];

waitingTimes[i] = turnAroundTimes[i] - burstTimes[i];

responseTimes[i] = waitingTimes[i];

totalTat += turnAroundTimes[i];

totalWt += waitingTimes[i];

double avgTat = (double) totalTat / numP;

double avgWt = (double) totalWt / numP;

System.out.println("Average Turn Around Time: " + avgTat);

System.out.println("Average Waiting Time: " + avgWt);

scanner.close();

}
5
}

Output :

SJF scheduling:
import java.util.*;

class sjf {

static int z = 1000000007;


static int sh = 100000;

static class util {


int id;
int at;
int bt;
int ct;
int tat;
int wt;
}

static util[] ar = new util[sh + 1];


static {
for (int i = 0; i < sh + 1; i++) {
ar[i] = new util();
}
}

6
static class util1 {
int p_id;
int bt1;
};

static util1 range = new util1();


static util1[] tr = new util1[4 * sh + 5];
static {
for (int i = 0; i < 4 * sh + 5; i++) {
tr[i] = new util1();
}
}

static int[] mp = new int[sh + 1];

static void update(int node, int st, int end, int ind, int id1, int b_t) {
if (st == end) {
tr[node].p_id = id1;
tr[node].bt1 = b_t;
return;
}
int mid = (st + end) / 2;
if (ind <= mid)
update(2 * node, st, mid, ind, id1, b_t);
else
update(2 * node + 1, mid + 1, end, ind, id1, b_t);
if (tr[2 * node].bt1 < tr[2 * node + 1].bt1) {
tr[node].bt1 = tr[2 * node].bt1;
tr[node].p_id = tr[2 * node].p_id;
} else {
tr[node].bt1 = tr[2 * node + 1].bt1;
tr[node].p_id = tr[2 * node + 1].p_id;
}
}

static util1 query(int node, int st, int end, int lt, int rt) {
if (end < lt || st > rt)
return range;
if (st >= lt && end <= rt)
return tr[node];
int mid = (st + end) / 2;
util1 lm = query(2 * node, st, mid, lt, rt);
util1 rm = query(2 * node + 1, mid + 1, end, lt, rt);
if (lm.bt1 < rm.bt1)
return lm;
return rm;
}

static void non_preemptive_sjf(int n) {


int counter = n;
int upper_range = 0;
7
int tm = Math.min(Integer.MAX_VALUE, ar[upper_range + 1].at);

while (counter != 0) {
for (; upper_range <= n;) {
upper_range++;
if (ar[upper_range].at > tm || upper_range > n) {
upper_range--;
break;
}

update(1, 1, n, upper_range, ar[upper_range].id, ar[upper_range].bt);


}

util1 res = query(1, 1, n, 1, upper_range);

if (res.bt1 != Integer.MAX_VALUE) {
counter--;
int index = mp[res.p_id];
tm += (res.bt1);

ar[index].ct = tm;
ar[index].tat = ar[index].ct - ar[index].at;
ar[index].wt = ar[index].tat - ar[index].bt;

update(1, 1, n, index, Integer.MAX_VALUE, Integer.MAX_VALUE);


} else {
tm = ar[upper_range + 1].at;
}
}
}
static void execute(int n) {
Arrays.sort(ar, 1, n, new Comparator<util>() {
public int compare(util a, util b) {
if (a.at == b.at)
return a.id - b.id;
return a.at - b.at;
}
});
for (int i = 1; i <= n; i++)
mp[ar[i].id] = i;

non_preemptive_sjf(n);
}
static void print(int n) {
int totalTAT = 0;
int totalWT = 0;
System.out.println("ProcessId Arrival Time Burst Time Completion Time Turn Around
Time Waiting Time");
for (int i = 1; i <= n; i++) {
System.out.printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n",
ar[i].id, ar[i].at, ar[i].bt, ar[i].ct, ar[i].tat, ar[i].wt);
8
totalTAT += ar[i].tat;
totalWT += ar[i].wt;
}
double avgTAT = (double) totalTAT / n;
double avgWT = (double) totalWT / n;
System.out.printf("\nAverage Turnaround Time: %.2f\n", avgTAT);
System.out.printf("Average Waiting Time: %.2f\n", avgWT);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of processes: ");
int n = sc.nextInt();
range.p_id = Integer.MAX_VALUE;
range.bt1 = Integer.MAX_VALUE;
for (int i = 1; i <= 4 * sh + 1; i++) {
tr[i].p_id = Integer.MAX_VALUE;
tr[i].bt1 = Integer.MAX_VALUE;
}
for (int i = 1; i <= n; i++) {
System.out.print("Enter arrival time for process " + i + ": ");
ar[i].at = sc.nextInt();
System.out.print("Enter burst time for process " + i + ": ");
ar[i].bt = sc.nextInt();

ar[i].id = i;
}
execute(n);
print(n);
}
}

Output:

9
SRTF scheduling:
import java.util.*;

class srtf{

static class Process {


int id;
int arrivalTime;
int burstTime;
int remainingTime;
int completionTime;
int turnaroundTime;
int waitingTime;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of processes: ");


int n = sc.nextInt();

Process[] processes = new Process[n];


for (int i = 0; i < n; i++) {
processes[i] = new Process();
processes[i].id = i + 1;
System.out.print("Enter arrival time for process " + (i + 1) + ": ");
processes[i].arrivalTime = sc.nextInt();
System.out.print("Enter burst time for process " + (i + 1) + ": ");
processes[i].burstTime = sc.nextInt();
processes[i].remainingTime = processes[i].burstTime;
10
}

Arrays.sort(processes, Comparator.comparingInt(p -> p.arrivalTime));

int completed = 0;
int currentTime = 0;
int prevTime = 0;
Process currentProcess = null;

while (completed != n) {
int minRemainingTime = Integer.MAX_VALUE;
Process nextProcess = null;

for (Process p : processes) {


if (p.arrivalTime <= currentTime && p.remainingTime > 0 && p.remainingTime <
minRemainingTime) {
minRemainingTime = p.remainingTime;
nextProcess = p;
}
}

if (nextProcess == null) {
currentTime++;
continue;
}

if (currentProcess != nextProcess) {
prevTime = currentTime;
currentProcess = nextProcess;
}

currentProcess.remainingTime--;
currentTime++;

if (currentProcess.remainingTime == 0) {
completed++;
currentProcess.completionTime = currentTime;
currentProcess.turnaroundTime = currentProcess.completionTime -
currentProcess.arrivalTime;
currentProcess.waitingTime = currentProcess.turnaroundTime -
currentProcess.burstTime;
currentProcess = null;
}
}
int totalTAT = 0;
int totalWT = 0;

System.out.println("ProcessId Arrival Time Burst Time Completion Time Turn Around


Time Waiting Time");
for (Process p : processes) {
System.out.printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n",
11
p.id, p.arrivalTime, p.burstTime, p.completionTime, p.turnaroundTime, p.waitingTime);
totalTAT += p.turnaroundTime;
totalWT += p.waitingTime;
}

double avgTAT = (double) totalTAT / n;


double avgWT = (double) totalWT / n;

System.out.printf("\nAverage Turnaround Time: %.2f\n", avgTAT);


System.out.printf("Average Waiting Time: %.2f\n", avgWT);
}
}

Output :

Priority scheduling :

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

class Process {
int id, arrivalTime, burstTime, priority, completionTime, waitingTime, turnaroundTime;

public Process(int id, int arrivalTime, int burstTime, int priority) {


this.id = id;
12
this.arrivalTime = arrivalTime;

this.burstTime = burstTime;
this.priority = priority;
}
}

public class Prp {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of processes: ");


int n = sc.nextInt();

Process[] processes = new Process[n];

// Input process details


for (int i = 0; i < n; i++) {
System.out.println("Enter details for Process " + (i + 1));
System.out.print("Arrival Time: ");
int arrivalTime = sc.nextInt();
System.out.print("Burst Time: ");
int burstTime = sc.nextInt();
System.out.print("Priority: ");
int priority = sc.nextInt();
processes[i] = new Process(i + 1, arrivalTime, burstTime, priority);
}

// Sort processes based on their arrival time and priority


Arrays.sort(processes, Comparator.comparingInt((Process p) -> p.arrivalTime)
.thenComparingInt(p -> p.priority));

int currentTime = 0;
for (Process process : processes) {
if (currentTime < process.arrivalTime) {
currentTime = process.arrivalTime;
}
process.completionTime = currentTime + process.burstTime;
process.turnaroundTime = process.completionTime - process.arrivalTime;
process.waitingTime = process.turnaroundTime - process.burstTime;
currentTime += process.burstTime;
}

// Display process details


System.out.println("\nProcess\tArrival\tBurst\tPriority\tCompletion\tTurnaround\tWaiting");
for (Process process : processes) {
System.out.println(process.id + "\t" +
process.arrivalTime + "\t" +
process.burstTime + "\t" +
process.priority + "\t\t" +
process.completionTime + "\t\t" +
13
process.turnaroundTime + "\t\t" +
process.waitingTime);
}

// Calculate and display average turnaround time and waiting time


double totalTurnaroundTime = 0;
double totalWaitingTime = 0;
for (Process process : processes) {
totalTurnaroundTime += process.turnaroundTime;
totalWaitingTime += process.waitingTime;
}

System.out.println("\nAverage Turnaround Time: " + (totalTurnaroundTime / n));


System.out.println("Average Waiting Time: " + (totalWaitingTime / n));

sc.close();
}
}

Output :

Round Robin :

import java.util.Scanner;

class RoundRobin {

// Method to find the waiting time for all processes


14
static void findWaitingTime(int processes[], int n, int bt[], int at[], int wt[], int quantum) {
int[] rem_bt = new int[n];
for (int i = 0; i < n; i++)
rem_bt[i] = bt[i];

int t = 0; // Current time


boolean[] done = new boolean[n];
int count = 0;

// Keep traversing processes in round robin manner


while (count < n) {
boolean allDone = true;

// Traverse all processes one by one repeatedly


for (int i = 0; i < n; i++) {
if (!done[i] && rem_bt[i] > 0) {
allDone = false; // There is a pending process

// If burst time of process is greater than quantum


if (rem_bt[i] > quantum) {
t += quantum;
rem_bt[i] -= quantum;
} else {
t += rem_bt[i];
wt[i] = t - bt[i] - at[i];
rem_bt[i] = 0;
done[i] = true;
count++;
}
}
}

// If all processes are done, exit the loop


if (allDone) break;
}
}

// Method to calculate turnaround time


static void findTurnAroundTime(int processes[], int n, int bt[], int at[], int wt[], int tat[]) {
for (int i = 0; i < n; i++)
tat[i] = bt[i] + wt[i];
}

// Method to calculate average time


static void findavgTime(int processes[], int n, int bt[], int at[], int quantum) {
int[] wt = new int[n];
int[] tat = new int[n];
int total_wt = 0, total_tat = 0;

// Function to find waiting time of all processes


findWaitingTime(processes, n, bt, at, wt, quantum);
15
// Function to find turnaround time for all processes
findTurnAroundTime(processes, n, bt, at, wt, tat);

// Display processes along with all details


System.out.println("PN " + " BT " + " AT " + " WT " + " TAT");

// Calculate total waiting time and total turnaround time


for (int i = 0; i < n; i++) {
total_wt += wt[i];
total_tat += tat[i];
System.out.println(" " + (i + 1) + "\t\t" + bt[i] + "\t " + at[i] + "\t " + wt[i] + "\t\t " + tat[i]);
}

System.out.println("Average waiting time = " + (float) total_wt / n);


System.out.println("Average turnaround time = " + (float) total_tat / n);
}

// Driver Method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Get the number of processes from the user


System.out.print("Enter the number of processes: ");
int n = sc.nextInt();

int[] processes = new int[n];


int[] burst_time = new int[n];
int[] arrival_time = new int[n];

// Get Burst time and Arrival time for each process from the user
for (int i = 0; i < n; i++) {
processes[i] = i + 1; // Process IDs are 1-based

System.out.print("Enter burst time for process " + (i + 1) + ": ");


burst_time[i] = sc.nextInt();

System.out.print("Enter arrival time for process " + (i + 1) + ": ");


arrival_time[i] = sc.nextInt();
}

// Get Time quantum from the user


System.out.print("Enter time quantum: ");
int quantum = sc.nextInt();

// Calculate average times


findavgTime(processes, n, burst_time, arrival_time, quantum);
}
}

16
Output :

2. Implement file storage allocation techniques: Contiguous (using array),


Linked–list allocation (using linked list) and indirect allocation (indexing).

Solution:

Contiguous Allocation (using Array)

In contiguous allocation, each file is stored in a contiguous block of memory. This technique
can be implemented using a simple array where each element represents a block of memory.

#include <iostream>
using namespace
std;

class ContiguousAllocation {
public:
int* memoryBlock;
int blockSize;

ContiguousAllocation(int
size) { memoryBlock = new
int[size]; blockSize = size;
for (int i = 0; i < blockSize; i++) {
17
memoryBlock[i] = -1; // -1 means empty block
}
}

void allocate(int start, int length)


{ if (start + length >
blockSize) {
cout << "Error: Not enough space to allocate the file!" <<
endl; return;
}

for (int i = start; i < start + length;


i++) { if (memoryBlock[i] != -1) {
cout << "Error: Block " << i << " is already allocated!" <<
endl; return;
}

18
memoryBlock[i] = 1; // 1 means allocated
}
cout << "File allocated successfully!" << endl;
}

void display() {
cout << "Memory Blocks: ";
for (int i = 0; i < blockSize; i++) {
cout << memoryBlock[i] << " ";
}
cout << endl;
}
};

int main() {
int size = 10;
ContiguousAllocation contigAlloc(size);

contigAlloc.display();
contigAlloc.allocate(3, 4); // Allocate 4 blocks starting from
block 3 contigAlloc.display();

contigAlloc.allocate(6, 4); // Try to allocate 4 blocks starting from block 6


contigAlloc.display();

return 0;
}
Output:

19
Linked-list Allocation
In linked-list allocation, each file is divided into blocks, and each block contains a pointer to the
next block. It can be implemented using a linked list.

#include <iostream>
using namespace
std;

class Block {
public:
int blockNum;
Block* next;

Block(int num) {
blockNum =
num; next =
nullptr;
}
};

class LinkedListAllocation {
public:
Block* head;

LinkedListAllocation(
) { head = nullptr;
}

void allocate(int blocks[], int numBlocks) {


Block* temp = nullptr;
for (int i = 0; i < numBlocks; i++) {
Block* newBlock = new
Block(blocks[i]); if (head == nullptr) {
head = newBlock;
} else {
temp->next = newBlock;
}
temp = newBlock;
}
cout << "File allocated using linked list!" << endl;
}

void display() {
Block* temp = head;
20
cout << "Allocated blocks: ";
while (temp != nullptr) {
cout << temp->blockNum << " ";

21
temp = temp->next;
}
cout << endl;
}
};

int main() {
int blocks[] = {2, 4, 6, 8}; // Blocks allocated for a file
LinkedListAllocation linkedAlloc;

linkedAlloc.allocate(blocks,
4); linkedAlloc.display();

return 0;
}
Output:

22
Indirect Allocation (Indexing)

In indirect allocation, a file is divided into blocks, and the block addresses are stored in an index
block. The index block points to the file’s data blocks.

#include <iostream>
#include <vector>
using namespace
std;
class IndirectAllocation
{ public:
vector<int> indexBlock;
vector<int> dataBlocks;

void allocate(const vector<int>&


fileBlocks) { for (int i = 0; i <
fileBlocks.size(); i++) {
dataBlocks.push_back(fileBlocks[i]);
}
indexBlock.push_back(dataBlocks.size());
cout << "File allocated with indirect allocation!" << endl;
}

void display() {
cout << "Index Block: ";
for (int i = 0; i < indexBlock.size();
i++) { cout << indexBlock[i] << " ";
}
cout << endl;

cout << "Data Blocks: ";


for (int i = 0; i < dataBlocks.size();
i++) { cout << dataBlocks[i] << " ";
}
cout << endl;
}
};

int main() {
IndirectAllocation indirectAlloc;
vector<int> fileBlocks = {5, 8, 9, 2}; // Blocks allocated for a file

indirectAlloc.allocate(fileBlocks);
indirectAlloc.display();

23
return 0;
}

24
Output:

25
3. Implement File Directories: Single Level, Two Level, Tree Level, Acyclic Graph
Directory.

Solution:

Single-Level Directory
#include <iostream>
#include <vector>
#include <string>
using namespace
std;

class SingleLevelDirectory {
vector<string> files;

public:
void createFile(const string& filename) {
files.push_back(filename);
cout << "File '" << filename << "' created." << endl;
}

void displayFiles() {
cout << "Files in Single-Level Directory:" <<
endl; for (const auto& file : files) {
cout << file << endl;
}
}
};

int main() {
SingleLevelDirectory dir;
dir.createFile("file1.txt");
dir.createFile("file2.txt");
dir.displayFiles();
return 0;
}
Output:

26
Two-Level Directory

#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace
std;

class TwoLevelDirectory {
map<string, vector<string>> userDirectories;

public:
void createFile(const string& user, const string& filename) {
userDirectories[user].push_back(filename);
cout << "File '" << filename << "' created for user '" << user << "'." << endl;
}

void displayFiles(const string& user) {


cout << "Files for user '" << user << "':" << endl;
for (const auto& file : userDirectories[user]) {
cout << file << endl;
}
}
};

int main() {
TwoLevelDirectory dir;
dir.createFile("user1", "file1.txt");
dir.createFile("user1", "file2.txt");
dir.createFile("user2", "file3.txt");
dir.displayFiles("user1");
dir.displayFiles("user2");
return 0;
}
Output:

27
Tree-Level Directory

#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace
std;

class TreeLevelDirectory {
map<string, vector<string>> directoryStructure;

public:
void createFile(const string& directory, const string& filename) {
directoryStructure[directory].push_back(filename);
cout << "File '" << filename << "' created in directory '" << directory << "'." << endl;
}

void displayFiles(const string& directory) {


cout << "Files in directory '" << directory << "':" << endl;
for (const auto& file : directoryStructure[directory]) {
cout << file << endl;
}
}
};

int main() {
TreeLevelDirectory dir;
dir.createFile("root", "file1.txt");
dir.createFile("root", "file2.txt");
dir.createFile("subdir", "file3.txt");
dir.displayFiles("root");
dir.displayFiles("subdir");
return 0;
}
Output:

28
Acyclic Graph Directory

#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace
std;

class AcyclicGraphDirectory {
map<string, vector<string>> directoryStructure;

public:
void linkDirectory(const string& parent, const string& child) {
directoryStructure[parent].push_back(child);
cout << "Directory '" << child << "' linked to '" << parent << "'." << endl;
}

void createFile(const string& directory, const string& filename) {


directoryStructure[directory].push_back(filename);
cout << "File '" << filename << "' created in directory '" << directory << "'." << endl;
}

void displayStructure(const string& directory) {


cout << "Contents of directory '" << directory << "':" <<
endl; for (const auto& content :
directoryStructure[directory]) {
cout << content << endl;
}
}
};

int main() {
AcyclicGraphDirectory dir;
dir.createFile("root", "file1.txt");
dir.linkDirectory("root", "subdir1");
dir.createFile("subdir1", "file2.txt");
dir.linkDirectory("subdir1", "sharedDir");
dir.createFile("sharedDir", "file3.txt");
dir.displayStructure("root");
dir.displayStructure("subdir1");
return 0;
}

29
Output:

30
4. Implement Disk Scheduling: FCFS, SSTF, SCAN, Circular SCAN, Look and
Circular Look.

Solution:

FCFS:

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

void fcfsDiskScheduling(const vector<int>& requests, int


head) { int totalHeadMovement = 0;
int currentHead = head;

cout << "Initial Head Position: " << head <<


"\n"; cout << "Sequence of Accessed Tracks: "
<< head;

for (const int& track : requests) {


totalHeadMovement += abs(track -
currentHead); currentHead = track;
cout << " -> " << track;
}

cout << "\nTotal Head Movement: " << totalHeadMovement << " tracks\n";
}

int main()
{ int
head;
int n;

cout << "Enter the number of disk requests:


"; cin >> n;

vector<int> requests(n);
cout << "Enter the disk track requests:
"; for (int i = 0; i < n; ++i) {
cin >> requests[i];
}

31
cout << "Enter the initial head
position: "; cin >> head;
fcfsDiskScheduling(requests, head);

return 0;
}

OUTPUT:

SSTF:

#include <iostream>
#include <vector>
#include <cmath>
#include <limits>
#include <algorithm>

using namespace std;

// Function to find the request with the smallest seek time


int findClosestRequest(const vector<int>& requests, int
currentHead) { int minDistance = numeric_limits<int>::max();
int closestRequest = -1;

for (int req : requests) {


int distance = abs(req -
currentHead); if (distance <
minDistance) {
minDistance = distance;
closestRequest = req;
}
}

return closestRequest;
32
}

void sstfDiskScheduling(vector<int> requests, int


head) { int totalHeadMovement = 0;
int currentHead = head;

cout << "Initial Head Position: " << head <<


"\n"; cout << "Sequence of Accessed Tracks: "
<< head;

while (!requests.empty()) {
// Find the closest request
int closestRequest = findClosestRequest(requests, currentHead);

// Update the total head movement


totalHeadMovement += abs(closestRequest - currentHead);

// Move the head to the closest request


currentHead = closestRequest;

// Print the closest request


cout << " -> " << closestRequest;

// Remove the processed request from the list


requests.erase(remove(requests.begin(), requests.end(), closestRequest), requests.end());
}

cout << "\nTotal Head Movement: " << totalHeadMovement << " tracks\n";
}

int main()
{ int
head;
int n;

cout << "Enter the number of disk requests:


"; cin >> n;

vector<int> requests(n);
cout << "Enter the disk track requests (valid range: 0 to
199): "; for (int i = 0; i < n; ++i) {
cin >> requests[i];
if (requests[i] < 0 || requests[i] > 199) {
cout << "Error: Request " << requests[i] << " is out of range. Please
33
restart.\n"; return 1;
}
}

cout << "Enter the initial head position (valid range: 0 to


199): "; cin >> head;
if (head < 0 || head > 199) {
cout << "Error: Initial head position is out of range. Please restart.\n";
return 1;
}

sstfDiskScheduling(requests, head);

return 0;
}

OUTPUT:

SCAN:

#include <iostream>
#include <vector>
#include <algorithm> // For sort
#include <cmath> // For abs()

using namespace std;

void cscanDiskScheduling(int start, int end, int head, vector<int>& requests, char
direction) { int totalHeadMovement = 0;
vector<int> left, right;

// Separate requests into two groups: those to the left and right of the
head for (int request : requests) {
if (request < head)

34
left.push_back(request);
else
right.push_back(request);
}

// Sort requests on both sides


sort(left.rbegin(), left.rend()); // Sort left in descending order
sort(right.begin(), right.end()); // Sort right in ascending order
cout << "Seek Sequence: ";

// First, move the head towards the right (towards


end) if (direction == 'R') {
// Service the requests to the right of the
head for (int r : right) {
totalHeadMovement += abs(r -
head); head = r;
cout << r << " ";
}
// Once we reach the end, jump to the beginning (0)
totalHeadMovement += (end - head); // move to 199 (or the end of the
disk) head = end;
cout << end << " ";

// Now move to the left (towards 0), servicing the


requests for (int r : left) {
totalHeadMovement += abs(r -
head); head = r;
cout << r << " ";
}
} else {
cout << "Invalid direction. Please use 'R' for right or 'L' for left.\n";
}

cout << "\nTotal Head Movement: " << totalHeadMovement << " tracks\n";
}
int main() {
int start, end, head;
char direction;

// Input the start and end of the cylinder


cout << "Enter the start and end of the cylinder (e.g., 0
199): "; cin >> start >> end;

// Input the head position (between start and


35
end) cout << "Enter the head position of the
cylinder: "; cin >> head;

// Input the direction (L for left, R for right)


cout << "Enter the direction (L for left, R for right):
"; cin >> direction;

// Input the number of blocks (disk


requests) int num;
cout << "Enter the number of blocks:
"; cin >> num;

vector<int> requests(num);
for (int i = 0; i < num; i++) {
cout << "Enter block " << i + 1 << ":
"; cin >> requests[i];
}

// Call the C-SCAN disk scheduling function


cscanDiskScheduling(start, end, head, requests, direction);

return 0;
}
OUTPUT:

36
CSCAN:
#include
<iostream>
#include <vector>
#include
<algorithm>
#include <cmath> // For abs()
function using namespace std;
void CSCAN(int arr[], int head, int size, int disk_size)
{
int seek_count = 0;
int distance, cur_track;
vector<int> left, right;
vector<int>
seek_sequence;

// Append the end values (0 and disk_size - 1) to represent the start and end of
the disk left.push_back(0); // Start of the disk (cylinder 0)
right.push_back(disk_size - 1); // End of the disk (maximum cylinder)

// Divide the requests into left and right of the


head for (int i = 0; i < size; i++) {
if (arr[i] < head)
left.push_back(arr[i]); // Tracks to the left of the
head if (arr[i] > head)
right.push_back(arr[i]); // Tracks to the right of the head
}

// Sort the left and right vectors


sort(left.begin(), left.end()); // Sort left in ascending order
sort(right.begin(), right.end()); // Sort right in ascending order

// First, service all the requests to the right of the


head for (int i = 0; i < right.size(); i++) {
cur_track = right[i];
seek_sequence.push_back(cur_trac
k); distance = abs(cur_track -
head); seek_count += distance;
head = cur_track;
}

// Once the head reaches the end (disk_size - 1), jump back to the beginning
(cylinder 0) seek_count += (disk_size - 1 - head); // Add the jump distance from
head to 0
37
head = 0; // Now, head is at cylinder 0

// Service the requests on the left side of the head (after returning to
cylinder 0) for (int i = 0; i < left.size(); i++) {
cur_track = left[i];
seek_sequence.push_back(cur_trac
k); distance = abs(cur_track -
head); seek_count += distance;
head = cur_track;
}

// Output the result


cout << "Total number of seek operations = " << seek_count <<
endl; cout << "Seek Sequence is:" << endl;
for (int i = 0; i < seek_sequence.size();
i++) { cout << seek_sequence[i] << " ";
}
cout << endl;
}

int main()
{
int size, head, disk_size;
// Taking input from the
user
cout << "Enter the number of
requests: "; cin >> size;

int arr[size];
cout << "Enter the disk size (maximum cylinder
number): "; cin >> disk_size;

cout << "Enter the initial position of the


head: "; cin >> head;

cout << "Enter the request sequence:


"; for (int i = 0; i < size; i++) {
cin >> arr[i];
}
// Call the CSCAN function
CSCAN(arr, head, size,
disk_size);

return 0;

38
}

39
OUTPUT:

LOOK SCHEDULING-

#include <iostream>
#include <algorithm>
#include <vector>
using namespace
std;

void LOOK(int requests[], int n, int head, string direction) {


vector<int> left, right, seek_sequence;
int total_movement = 0;

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


if (requests[i] < head)
left.push_back(requests[i]);
else
right.push_back(requests[i]);
}

sort(left.begin(), left.end());
sort(right.begin(), right.end());

if (direction == "left") {

for (int i = left.size() - 1; i >= 0; i--) {

40
total_movement += abs(head -
left[i]); head = left[i];
seek_sequence.push_back(head);
}

for (int i = 0; i < right.size(); i++) {


total_movement += abs(head -
right[i]); head = right[i];
seek_sequence.push_back(head);
}
} else if (direction == "right") {

for (int i = 0; i < right.size(); i++) {


total_movement += abs(head -
right[i]); head = right[i];
seek_sequence.push_back(head);
}

for (int i = left.size() - 1; i >= 0; i--) {


total_movement += abs(head -
left[i]); head = left[i];
seek_sequence.push_back(head);
}
}

cout << "Total Head Movement in LOOK: " << total_movement << endl; cout
<< "Seek Sequence: ";
for (int i = 0; i < seek_sequence.size(); i++) { cout
<< seek_sequence[i];
if (i < seek_sequence.size() - 1) cout << " -> ";
}
cout << endl;
}

int main() {
int n, head;
string direction;

cout << "Enter number of requests: ";


cin >> n;
int requests[n];
41
cout << "Enter the requests: ";
for (int i = 0; i < n; i++) cin >> requests[i];
cout << "Enter initial head position: ";
cin >> head;

cout << "Enter the direction (left/right): ";


cin >> direction;

transform(direction.begin(), direction.end(), direction.begin(), ::tolower);


LOOK(requests, n, head, direction);
return 0;
}
OUTPUT-

C-LOOK SCHEDULING-

#include <bits/stdc++.h>
using namespace std;
int size = 8;
int disk_size = 200;

void CLOOK(int arr[], int head)


{
int seek_count = 0;
int distance, cur_track;
vector<int> left, right;
vector<int> seek_sequence;

int size = 8;
for (int i = 0; i < size; i++)
{ if (arr[i] < head)
left.push_back(arr[i]);
if (arr[i] > head)
right.push_back(arr[i]);
}
42
std::sort(left.begin(), left.end());
std::sort(right.begin(), right.end());
for (int i = 0; i < right.size(); i++) {
cur_track = right[i];

seek_sequence.push_back(cur_trac
k); distance = abs(cur_track -
head); seek_count += distance;

head = cur_track;
}
seek_count += abs(head - left[0]);
head = left[0];

for (int i = 0; i < left.size(); i++) {


cur_track = left[i];

seek_sequence.push_back(cur_trac
k); distance = abs(cur_track -
head); seek_count += distance;
head = cur_track;
}

cout << "Total number of seek operations = "


<< seek_count << endl;
cout << "Seek Sequence is" <<
endl;

for (int i = 0; i < seek_sequence.size(); i++) { cout


<< seek_sequence[i] << endl;
}
}
int main()
{
int size = 8;
int arr[size] = { 176, 79, 34, 60,92, 11, 41, 114 };
int head = 50;
cout << "Initial position of head: " << head << endl;

43
CLOOK(arr, head);
return 0;
}
OUTPUT:

44
5. Implement of different Network Topologies. Locating different interfaces,
routers and switches. Studying different pools of IP addresses.

Solution:

BUS TOPOLOGY_-

STAR TOPOLOGY_-

45
RING TOPOLOGY_-

MESH TOPOLOGY_-

46
6. Learn and observe the usage of different networking commands e.g.
PING, TRACEROUTE. Learning remote login using telnet session.
Measuring typical average delays between different locations of the
network.
Solution:

1. PING Command

The PING command is used to check the network connectivity between your system
and a target system (usually a remote server). It sends Internet Control Message
Protocol (ICMP) Echo Request messages and measures the round-trip time for the
messages to reach the destination.

Syntax : ping <hostname or IP address>


Example :

The output shows the round-trip time and the average time it took to send and receive
the request.

2. TRACEROUTE Command

The TRACEROUTE command is used to trace the path that packets take from your
machine to a destination system, showing each intermediate router’s IP address and
the time taken to reach each hop.

Syntax: traceroute <hostname or IP address>

Example :

47
The TRACEROUTE output displays each hop along the network path and the round-trip
times for each. It helps diagnose where the network delays are occurring.

48

You might also like