0% found this document useful (0 votes)
2 views35 pages

OS Lab Report

This lab report presents various operating system scheduling algorithms, including FCFS, LRU, Priority, SJF, Optimal LRU, Page Replacement, and Round Robin. Each algorithm is accompanied by source code written in Java, demonstrating how to implement these scheduling techniques. The report is submitted by Sajal Udash as part of the Artificial Intelligence course at Kantipur College of Management and Information Technology.

Uploaded by

udashsajal8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views35 pages

OS Lab Report

This lab report presents various operating system scheduling algorithms, including FCFS, LRU, Priority, SJF, Optimal LRU, Page Replacement, and Round Robin. Each algorithm is accompanied by source code written in Java, demonstrating how to implement these scheduling techniques. The report is submitted by Sajal Udash as part of the Artificial Intelligence course at Kantipur College of Management and Information Technology.

Uploaded by

udashsajal8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

A

LAB REPORT

ON
Operating System

BY

Sajal Udash

Exam Roll No: 11369/20

Submitted to:
Indra PC

Department of Computer Science


Kantipur College of Management and Information Technology

In partial fulfillment of the requirements for the Course


Artificial Intelligience

Mid Baneshwor, Kathmandu

Jan, 2025

1
Contents
1. Write a program of FCFC algorithm in context of os?.........................................................................3
1.1. Source Code.....................................................................................................................................3
2. Write a program of Lru algorithm in context of os?.............................................................................6
2. Write a program of Priority algorithm in context of os?......................................................................8
1. Write a program of Sjf algorithm in context of os?............................................................................10
2. Write a program of Optimal LRU in context of os?..........................................................................14
3. Write a program of Page Replacement in context of os?.................................................................17
4. Write a program of Round Robin in context of os?..........................................................................21
5. Write a program of Banker Algorithm in context of os?...................................................................23
6. Write a program of Worst Fit in context of os?.................................................................................27
7. Write a program of Base Fit in context of os?....................................................................................31
8. Write a program of Next Fit in context of os?....................................................................................34

2
1. Write a program of FCFC algorithm in context of os?
1.1. Source Code

import java.util.Scanner;
class Process {
int pid;
int arrivalTime;
int burstTime;
int completionTime;
int turnAroundTime;
int waitingTime;

public Process(int pid, int arrivalTime, int burstTime) {


this.pid = pid;
this.arrivalTime = arrivalTime;
this.burstTime = burstTime;
}
}

public class FCFS {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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


int n = scanner.nextInt();

Process[] processes = new Process[n];

3
for (int i = 0; i < n; i++) {
System.out.print("Enter arrival time of process " + (i + 1) + ": ");
int arrivalTime = scanner.nextInt();
System.out.print("Enter burst time of process " + (i + 1) + ": ");
int burstTime = scanner.nextInt();
processes[i] = new Process(i + 1, arrivalTime, burstTime);
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (processes[i].arrivalTime > processes[j].arrivalTime) {
Process temp = processes[i];
processes[i] = processes[j];
processes[j] = temp;
}
}
}
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.completionTime;
}
System.out.println("\nProcess\tArrival\tBurst\tCompletion\tTurnaround\tWaiting");
for (Process process : processes) {
System.out.println(process.pid + "\t" + process.arrivalTime + "\t" + process.burstTime + "\t" +
process.completionTime + "\t\t" + process.turnAroundTime + "\t\t" + process.waitingTime);

4
}
double totalTurnAroundTime = 0, totalWaitingTime = 0;
for (Process process : processes) {
totalTurnAroundTime += process.turnAroundTime;
totalWaitingTime += process.waitingTime;
}

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


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

scanner.close();
}
}

Output

5
2. Write a program of Lru algorithm in context of os?
2.1. Source code
import java.util.*;
public class LRUCache {
private final int capacity;
private final LinkedHashSet<Integer> cache;
public LRUCache(int capacity) {
this.capacity = capacity;
this.cache = new LinkedHashSet<>();
}
public void accessPage(int page) {
if (cache.contains(page)) {
cache.remove(page);
}
else if (cache.size() == capacity) {
int first = cache.iterator().next(); // Get the first element
cache.remove(first); // Remove the least recently used page
System.out.println("Page " + first + " removed (LRU).");
}
cache.add(page);
System.out.println("Page " + page + " added.");
}
public void displayCache() {
System.out.println("Cache: " + cache);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the capacity of the LRU cache: ");

6
int capacity = scanner.nextInt();

LRUCache lruCache = new LRUCache(capacity);

System.out.println("Enter the sequence of page references (-1 to stop):");


while (true) {
int page = scanner.nextInt();
if (page == -1) break;

lruCache.accessPage(page);
lruCache.displayCache();
}

scanner.close();
}
}

OUTPUT

1. Write a program of Priority algorithm in context of os?


1.1. Source code

7
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

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

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


this.id = id;
this.arrivalTime = arrivalTime;
this.burstTime = burstTime;
this.priority = priority;
}
}
public class PriorityScheduling {
public static void main(String[] args) {
List<Process> processes = new ArrayList<>();
processes.add(new Process(1, 0, 10, 2));
processes.add(new Process(2, 2, 5, 0));
processes.add(new Process(3, 3, 8, 1));
priorityScheduling(processes);

System.out.println("Process\tArrival\tBurst\tPriority\tCompletion\tTurnaround\tWaiting");
for (Process p : processes) {
System.out.printf("P%d\t%d\t%d\t%d\t\t%d\t\t%d\t\t%d\n",
p.id, p.arrivalTime, p.burstTime, p.priority,
p.completionTime, p.turnaroundTime, p.waitingTime);
}
}

public static void priorityScheduling(List<Process> processes) {

processes.sort(Comparator.comparingInt((Process p) -> p.priority).thenComparingInt(p ->


p.arrivalTime));

int currentTime = 0;
for (Process process : processes) {
// If the CPU is idle, move the current time to the process's arrival time
if (currentTime < process.arrivalTime) {
currentTime = process.arrivalTime;

8
}

process.completionTime = currentTime + process.burstTime;


currentTime += process.burstTime;

process.turnaroundTime = process.completionTime - process.arrivalTime;

process.waitingTime = process.turnaroundTime - process.burstTime;


}
}
}

Output

1. Write a program of Sjf algorithm in context of os?


Source code
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

9
class Process {
int id;
int arrivalTime;
int burstTime;
int completionTime;
int turnaroundTime;
int waitingTime;

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


this.id = id;
this.arrivalTime = arrivalTime;
this.burstTime = burstTime;
}
}

public class SJFScheduling {


public static void main(String[] args) {

List<Process> processes = new ArrayList<>();


processes.add(new Process(1, 0, 7));
processes.add(new Process(2, 2, 4));
processes.add(new Process(3, 4, 1));
processes.add(new Process(4, 5, 4));

sjfScheduling(processes);

System.out.println("Process\tArrival\tBurst\tCompletion\tTurnaround\tWaiting");
for (Process p : processes) {
System.out.printf("P%d\t%d\t%d\t%d\t\t%d\t\t%d\n",

10
p.id, p.arrivalTime, p.burstTime,
p.completionTime, p.turnaroundTime, p.waitingTime);
}
}

public static void sjfScheduling(List<Process> processes) {

List<Process> completed = new ArrayList<>();


int currentTime = 0;

while (completed.size() < processes.size()) {

List<Process> available = new ArrayList<>();


for (Process p : processes) {
if (!completed.contains(p) && p.arrivalTime <= currentTime) {
available.add(p);
}
}

if (!available.isEmpty()) {
Process shortest = available.stream()
.min(Comparator.comparingInt(p -> p.burstTime))
.orElse(null);

shortest.completionTime = currentTime + shortest.burstTime;


currentTime += shortest.burstTime;

11
shortest.turnaroundTime = shortest.completionTime - shortest.arrivalTime;
shortest.waitingTime = shortest.turnaroundTime - shortest.burstTime;

completed.add(shortest);
} else {

currentTime++;
}
}
}
}

Output

12
13
2. Write a program of Optimal LRU in context of os?
2.1. Source code
import java.util.*;

public class OptimalPageReplacement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of frames: ");
int frameCount = scanner.nextInt();
System.out.print("Enter the number of pages: ");
int pageCount = scanner.nextInt();
int[] pages = new int[pageCount];
System.out.println("Enter the reference string (page numbers):");
for (int i = 0; i < pageCount; i++) {
pages[i] = scanner.nextInt();
}
List<Integer> frames = new ArrayList<>();
int pageFaults = 0;

System.out.println("\nPage Replacement Process:");


for (int i = 0; i < pageCount; i++) {
int currentPage = pages[i];
if (!frames.contains(currentPage)) {
pageFaults++;
if (frames.size() == frameCount) {
int pageToReplace = findOptimalPage(frames, pages, i + 1);
System.out.println("Page " + pageToReplace + " removed (Optimal replacement).");
frames.remove(Integer.valueOf(pageToReplace));
}
frames.add(currentPage);

14
System.out.println("Page " + currentPage + " added to the frame.");
} else {
System.out.println("Page " + currentPage + " accessed (No page fault).");
}
System.out.println("Current frames: " + frames);
}

System.out.println("\nTotal page faults: " + pageFaults);


scanner.close();
}
private static int findOptimalPage(List<Integer> frames, int[] pages, int startIndex) {
Map<Integer, Integer> futureUsage = new HashMap<>();
for (int framePage : frames) {
boolean found = false;
for (int j = startIndex; j < pages.length; j++) {
if (pages[j] == framePage) {
futureUsage.put(framePage, j);
found = true;
break;
}
}
if (!found) {
futureUsage.put(framePage, Integer.MAX_VALUE);
}
}
int pageToReplace = -1;
int farthestUsage = -1;
for (int framePage : frames) {
int nextUse = futureUsage.get(framePage);
if (nextUse > farthestUsage) {

15
farthestUsage = nextUse;
pageToReplace = framePage;
}
}

return pageToReplace;
}
}

Output

3. Write a program of Page Replacement in context of os?


Source code
import java.util.*;

16
public class PageReplacement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of frames: ");
int frameCount = scanner.nextInt();
System.out.print("Enter the number of pages: ");
int pageCount = scanner.nextInt();
int[] pages = new int[pageCount];
System.out.println("Enter the reference string (page numbers):");
for (int i = 0; i < pageCount; i++) {
pages[i] = scanner.nextInt();
}
Set<Integer> frames = new HashSet<>();
Map<Integer, Integer> pageIndices = new HashMap<>();
int pageFaults = 0;

System.out.println("\nPage Replacement Process:");


for (int i = 0; i < pageCount; i++) {
int currentPage = pages[i];
if (!frames.contains(currentPage)) {
pageFaults++;
if (frames.size() == frameCount) {
int lruPage = findLeastRecentlyUsed(pageIndices);
frames.remove(lruPage);
pageIndices.remove(lruPage);
System.out.println("Page " + lruPage + " removed (Least Recently Used).");
frames.add(currentPage);
System.out.println("Page " + currentPage + " added to the frame.");
} else {

17
System.out.println("Page " + currentPage + " accessed (No page fault).");
}
pageIndices.put(currentPage, i);
System.out.println("Current frames: " + frames);
}

System.out.println("\nTotal page faults: " + pageFaults);


scanner.close();
}
private static int findLeastRecentlyUsed(Map<Integer, Integer> pageIndices) {
int lruPage = -1;
int minIndex = Integer.MAX_VALUE;

for (Map.Entry<Integer, Integer> entry : pageIndices.entrySet()) {


if (entry.getValue() < minIndex) {
minIndex = entry.getValue();
lruPage = entry.getKey();
}
}

return lruPage;
}
}

Output

18
19
4. Write a program of Round Robin in context of os?
Source code

import java.util.LinkedList;
import java.util.Queue;

class Process {
int id;
int arrivalTime;
int burstTime;
int remainingTime;
int completionTime;
int turnaroundTime
int waitingTime;

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


this.id = id;
this.arrivalTime = arrivalTime;
this.burstTime = burstTime;
this.remainingTime = burstTime;
}
}

public class RoundRobin {


public static void main(String[] args) {
Process[] processes = {
new Process(1, 0, 5),
new Process(2, 1, 3),
new Process(3, 2, 8),
new Process(4, 3, 6)

20
};
int timeQuantum = 3;
roundRobinScheduling(processes, timeQuantum);
System.out.println("Process\tArrival\tBurst\tCompletion\tTurnaround\tWaiting");
for (Process p : processes) {
System.out.printf("P%d\t%d\t%d\t%d\t\t%d\t\t%d\n",
p.id, p.arrivalTime, p.burstTime,
p.completionTime, p.turnaroundTime, p.waitingTime);
}
}

public static void roundRobinScheduling(Process[] processes, int timeQuantum) {


Queue<Process> readyQueue = new LinkedList<>();
int currentTime = 0;
int processIndex = 0;
while (processIndex < processes.length && processes[processIndex].arrivalTime <= currentTime) {
readyQueue.add(processes[processIndex]);
processIndex++;
}

while (!readyQueue.isEmpty()) {
Process currentProcess = readyQueue.poll();
int executionTime = Math.min(currentProcess.remainingTime, timeQuantum);
currentProcess.remainingTime -= executionTime;
currentTime += executionTime;
while (processIndex < processes.length && processes[processIndex].arrivalTime <= currentTime)
{
readyQueue.add(processes[processIndex]);
processIndex++;
}

21
if (currentProcess.remainingTime > 0) {
readyQueue.add(currentProcess);
} else {
currentProcess.completionTime = currentTime;
currentProcess.turnaroundTime = currentProcess.completionTime - currentProcess.arrivalTime;
currentProcess.waitingTime = currentProcess.turnaroundTime - currentProcess.burstTime;
}
}
}
}

Output

5. Write a program of Banker Algorithm in context of os?


Source code

22
import java.util.Scanner;

public class BankersAlgorithm {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of processes: ");
int numProcesses = sc.nextInt();
System.out.print("Enter the number of resources: ");
int numResources = sc.nextInt();
int[][] allocation = new int[numProcesses][numResources];
System.out.println("Enter the Allocation matrix:");
for (int i = 0; i < numProcesses; i++) {
for (int j = 0; j < numResources; j++) {
allocation[i][j] = sc.nextInt();
}
}
int[][] maximum = new int[numProcesses][numResources];
System.out.println("Enter the Maximum matrix:");
for (int i = 0; i < numProcesses; i++) {
for (int j = 0; j < numResources; j++) {
maximum[i][j] = sc.nextInt();
}
}
int[] available = new int[numResources];
System.out.println("Enter the Available resources:");
for (int i = 0; i < numResources; i++) {
available[i] = sc.nextInt();
}

23
int[][] need = new int[numProcesses][numResources];
for (int i = 0; i < numProcesses; i++) {
for (int j = 0; j < numResources; j++) {
need[i][j] = maximum[i][j] - allocation[i][j];
}
}
boolean isSafe = bankersAlgorithm(allocation, maximum, available, need, numProcesses,
numResources);

if (isSafe) {
System.out.println("The system is in a safe state.");
} else {
System.out.println("The system is NOT in a safe state.");
}

sc.close();
}

public static boolean bankersAlgorithm(int[][] allocation, int[][] maximum, int[] available,


int[][] need, int numProcesses, int numResources) {
boolean[] finished = new boolean[numProcesses];
int[] safeSequence = new int[numProcesses];
int[] work = available.clone();
int count = 0;

while (count < numProcesses) {


boolean found = false;
for (int i = 0; i < numProcesses; i++) {
if (!finished[i]) {
boolean canProceed = true;

24
for (int j = 0; j < numResources; j++) {
if (need[i][j] > work[j]) {
canProceed = false;
break;
}
}

if (canProceed) {
for (int j = 0; j < numResources; j++) {
work[j] += allocation[i][j];
}
safeSequence[count++] = i;
finished[i] = true;
found = true;
}
}
}

if (!found) {

return false;
}
}

System.out.print("Safe Sequence: ");


for (int i = 0; i < numProcesses; i++) {
System.out.print("P" + safeSequence[i] + " ");
}
System.out.println();

25
return true;
}
}

Output

6. Write a program of Worst Fit in context of os?


Source code
import java.util.Scanner;

public class WorstFit {


public static void main(String[] args) {

26
Scanner scanner = new Scanner(System.in);

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


int blockCount = scanner.nextInt();
int[] blocks = new int[blockCount];
boolean[] allocated = new boolean[blockCount];
System.out.println("Enter sizes of the memory blocks:");
for (int i = 0; i < blockCount; i++) {
blocks[i] = scanner.nextInt();
}
System.out.print("Enter number of processes: ");
int processCount = scanner.nextInt();
int[] processes = new int[processCount];
System.out.println("Enter sizes of the processes:");
for (int i = 0; i < processCount; i++) {
processes[i] = scanner.nextInt();
}
for (int i = 0; i < processCount; i++) {
int worstIndex = -1;
for (int j = 0; j < blockCount; j++) {
if (!allocated[j] && blocks[j] >= processes[i]) {
if (worstIndex == -1 || blocks[j] > blocks[worstIndex]) {
worstIndex = j;
}
}
}
if (worstIndex != -1) {
System.out.println("Process " + (i + 1) + " of size " + processes[i]
+ " allocated to block " + (worstIndex + 1) + " of size " + blocks[worstIndex]);
blocks[worstIndex] -= processes[i]; // Reduce the block size

27
allocated[worstIndex] = blocks[worstIndex] == 0; // Mark block as allocated if fully used
} else {
System.out.println("Process " + (i + 1) + " of size " + processes[i] + " cannot be
allocated.");
}
}
System.out.println("\nRemaining memory in each block:");
for (int i = 0; i < blockCount; i++) {
System.out.println("Block " + (i + 1) + ": " + blocks[i]);
}

scanner.close();
}
}

Output

28
29
7. Write a program of Base Fit in context of os?
Source code

import java.util.Scanner;
public class BestFit {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of memory blocks: ");
int blockCount = scanner.nextInt();
int[] blocks = new int[blockCount
System.out.println("Enter the sizes of the memory blocks:");
for (int i = 0; i < blockCount; i++) {
blocks[i] = scanner.nextInt();
}
System.out.print("Enter the number of processes: ");
int processCount = scanner.nextInt();
int[] processes = new int[processCount];
System.out.println("Enter the sizes of the processes:");
for (int i = 0; i < processCount; i++) {
processes[i] = scanner.nextInt();
}
for (int i = 0; i < processCount; i++) {
int bestIndex = -1;
for (int j = 0; j < blockCount; j++) {
if (blocks[j] >= processes[i]) {
if (bestIndex == -1 || blocks[j] < blocks[bestIndex]) {
bestIndex = j;
}
}
}

30
if (bestIndex != -1) {
System.out.println("Process " + (i + 1) + " of size " + processes[i]
+ " allocated to block " + (bestIndex + 1) + " of size " + blocks[bestIndex]);
blocks[bestIndex] -= processes[i];
} else {
System.out.println("Process " + (i + 1) + " of size " + processes[i] + " cannot be
allocated.");
}
}

System.out.println("\nRemaining memory in each block:");


for (int i = 0; i < blockCount; i++) {
System.out.println("Block " + (i + 1) + ": " + blocks[i]);
}

scanner.close();
}
}

Output

31
32
8. Write a program of Next Fit in context of os?
Source code
import java.util.Scanner;

public class NextFit {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of memory blocks: ");
int blockCount = scanner.nextInt();
int[] blocks = new int[blockCount];
System.out.println("Enter the sizes of the memory blocks:");
for (int i = 0; i < blockCount; i++) {
blocks[i] = scanner.nextInt();
}
System.out.print("Enter the number of processes: ");
int processCount = scanner.nextInt();
int[] processes = new int[processCount];
System.out.println("Enter the sizes of the processes:");
for (int i = 0; i < processCount; i++) {
processes[i] = scanner.nextInt();
}

int lastAllocatedIndex = 0;

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


boolean allocated = false;
for (int j = 0; j < blockCount; j++) {
int index = (lastAllocatedIndex + j) % blockCount;
if (blocks[index] >= processes[i]) {
System.out.println("Process " + (i + 1) + " of size " + processes[i]

33
+ " allocated to block " + (index + 1) + " of size " + blocks[index]);
blocks[index] -= processes[i];
lastAllocatedIndex = index;
allocated = true;
break;
}
}

if (!allocated) {
System.out.println("Process " + (i + 1) + " of size " + processes[i] + " cannot be
allocated.");
}
}
System.out.println("\nRemaining memory in each block:");
for (int i = 0; i < blockCount; i++) {
System.out.println("Block " + (i + 1) + ": " + blocks[i]);
}

scanner.close();
}
}

Output

34
35

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy