OPERATING SYSYTEM LAB Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 39

THE OXFORD COLLEGE OF ENGINEERING

BOMMANAHALLI, HOSUR ROAD, BENGALURU-560068.


(Affiliated to Visvesvaraya Technological University, Belgaum)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

Subject Name: OPERATING SYSTEMS


Subject Code : BCS303
Semester : III
Academic Year: 2023-24

Prepared by: Prof. Shruthi K Reddy


Children’s Education Society ®
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
THE OXFORD COLLEGE OF ENGINEERING
Hosur Road, Bommanahalli, Bengaluru-560 068
Website:www.theoxford.edu Email : [email protected]
(Approved by AICTE, New Delhi, Accredited by NBA, NAAC, New Delhi & Affiliated to VTU, Belgaum)

INSTITUTION

Vision
To be a Respected and Most Sought after Engineering Educational Institution Engaged in
Equipping Individuals Capable of Building Learning Organizations in the New Millennium.

Mission
To Develop Competent Students with Good Value Systems to Face Challenges of the
Continuously Changing World.

DEPARTMENT

Vision
To establish the department as a renowned center of excellence in the area of scientific
education, research with industrial guidance, and exploration of the latest advances in the rapidly
changing field of computer science.

Mission
To produce technocrats with creative technical knowledge and intellectual skills to sustain and
excel in the highly demanding world with confidence.

Program Educational Objectives (PEO)


1. To create graduates equipped with life-long learning skills and have a successful
professional career in IT industry.
2. To prepare graduates to pursue higher education and get inclined towards research &
development in computer science engineering.
3. To provide adequate training and opportunities, with exposure to emerging cutting edge
technologies and to work in teams on multidisciplinary projects with effective
communication skills and leadership qualities.

1
Program Specific Outcomes (PSO)

1. To design efficient algorithms and develop effective code for real-time computations.
2. To apply software engineering principles in developing optimal software solutions.

2
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING
THE OXFORD COLLEGE OF ENGINEERING
Hosur Road, Bommanahalli, Bengaluru-560 068
Website:www.theoxford.edu Email : [email protected]
Academic Year: 2023 -2024 (III sem)
Subject: Operating Systems Sub Code: BCS303

Course Outcomes (COs)

CO’s Descripti Blooms


on Level
CO1 Explain the structure and functionality of operating system L2
Apply appropriate CPU scheduling algorithms for the given
CO2 problem. L3

Analyse the various techniques for process synchronization and


CO3 L3
deadlock handling.

CO4 Apply the various techniques for memory management L2

CO5 Explain file and secondary storage management strategies.. L3

CO6 Describe the need for information protection mechanisms L2

P
O PO1 PO PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO1 PO1 PO
2 0 1 12
CO
CO1 2 - 2 - - - - - - - - 2
CO2 1 - 2 - - - - - - - - 3

CO3 1 - 2 - - - - - - - - 2

CO4 1 - 2 - - - - - - - - 2

CO5 1 - 2 - - - - - - - - 2

3
Sl.N Experiments
O
1 Develop a c program to implement the Process system calls (fork (), exec(), wait(), create
process, terminate process)

2 Simulate the following CPU scheduling algorithms to find turnaround time and waiting time
a) FCFS
b) SJF c) Round Robin d) Priority.
3 Develop a C program to simulate producer-consumer problem using semaphores.

4 Develop a C program which demonstrates interprocess communication between a


reader process and a writer process. Use mkfifo, open, read, write and close APIs
in your program.
5
Develop a C program to simulate Bankers Algorithm for DeadLock Avoidance.
6 Develop a C program to simulate the following contiguous memory allocation Techniques:
a) Worst fit b) Best fit c) First fit.
7 Develop a C program to simulate page replacement algorithms:
a) FIFO b) LRU
8 Simulate following File Organization Techniques

a) Single level directory b) Two level directory


9 Develop a C program to simulate the Linked file allocation strategies.

10 Develop a C program to simulate SCAN disk scheduling algorithm.

4
EX.NO.1: IMPLEMENTATION OF FORK, EXEC, CREATE,EXIT, WAIT
SYSTEM CALLS.

AIM: To Develop a c program to implement the Process system calls (fork (), exec(), wait(), create
process,terminate process)

DESCRIPTION:

System calls Explanation


fork(): This system call creates a new process by duplicating the existing
process. The child process gets a new process ID (PID), which is
different from the parent process.
exec(): This system call is used to execute a new program in the current
process. In the child process,
execvp() is used to execute the echo command.
wait(): The parent process uses wait() to wait for the termination of the child
process. The exit status of the child process is collected using the status
variable.
exit(): This function is called to terminate the process. If exec() fails, the child
process will exit with a failure status.

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t childPid;
int status;
childPid = fork();
if (childPid < 0)
{
perror("Fork failed");
exit(EXIT_FAILURE);
}
else if (childPid == 0)
{
printf("Child process: PID = %d\n", getpid());
char *args[] = {"echo", "Hello from the child process!", NULL};
execvp(args[0], args);
perror("Exec failed");
exit(EXIT_FAILURE);
}
else {
printf("Parent process: PID = %d, Child PID = %d\n", getpid(), childPid);
wait(&status);
if (WIFEXITED(status)) {

5
printf("Child process terminated with status: %d\n", WEXITSTATUS(status));
} else {
printf("Child process terminated abnormally\n");
}
}
return 0;
}

OUTPUT:
[root@localhost ~]# ./a.out tst date
Child process:
Child process id : 3137
Sat Apr 10 02:45:32 IST 2010
Parent Process:
Parent Process id:3136 sd dsaASD
[root@localhost ~]# cat tst sd dsaASD

RESULT: Thus the program for process management was written and successfully executed

6
EX.NO.2: IMPLEMENTATION OF CPU SCHEDULING ALGORITHMS TO FIND
TURNAROUND TIME AND WAITING TIME.

AIM: To Simulate the following CPU scheduling algorithms to find turnaround time and waiting
time a)FCFS b) SJF c) Round Robin d) Priority.

DESCRIPTION:

Scheduling Explanation
Algorithm
FCFS

SJF
Round
Robin
Priority.

PROGRAM
#include <stdio.h>

void findWaitingTime(int processes[ ], int n, int bt[], int wt[])


{
wt[0] = 0;
for (int i = 1; i < n; i++) {
wt[i] = bt[i - 1] + wt[i - 1];
}
}

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

void findAvgTime(int processes[], int n, int bt[])


{
int wt[n], tat[n];
findWaitingTime(processes, n, bt, wt);
findTurnAroundTime(processes, n, bt, wt, tat);
float total_wt = 0, total_tat = 0;
for (int i = 0; i < n; i++) {
total_wt += wt[i];
total_tat += tat[i];
}

printf("FCFS Scheduling:\n");

7
printf("Average Waiting Time: %.2f\n", total_wt / n);
printf("Average Turnaround Time: %.2f\n", total_tat / n);
}

int main()
{
int processes[] = {1, 2, 3};
int n = sizeof (processes) / sizeof(processes[0]);
int burst_time[] = {10, 5, 8};
findAvgTime(processes, n, burst_time);
return 0;
}

OUTPUT:

FCFS Scheduling:
Average Waiting Time: 8.33
Average Turnaround Time: 16.00

i) Shortest Job First


#include <stdio.h>

void findWaitingTime(int processes[], int n, int bt[], int wt[]) {


int rt[n];
for (int i = 0; i < n; i++) {
rt[i] = bt[i];
}

int complete = 0, t = 0, minm = 9999, shortest = 0, finish_time;


int check = 0;

// Process until all processes are completed


while (complete != n) {
for (int j = 0; j < n; j++) {
if ((rt[j] <= t) && (rt[j] < minm) && (rt[j] > 0))
{
minm = rt[j];
shortest = j;
check = 1;
}
}

if (check == 0) {

8
t++;
continue;
}

// Reduce remaining time and calculate waiting time


rt[shortest] = 0;
finish_time = t + 1;
wt[shortest] = finish_time - bt[shortest];
t++;

// Update minimum
minm = rt[shortest];
if (minm == 0) {
minm = 9999;
}

// Check if the process is finished


if (rt[shortest] == 0) {
complete++;
}
}
}

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

void findAvgTime(int processes[], int n, int bt[]) {


int wt[n], tat[n];
findWaitingTime(processes, n, bt, wt);
findTurnAroundTime(processes, n, bt, wt, tat);

float total_wt = 0, total_tat = 0;


for (int i = 0; i < n; i++) {
total_wt += wt[i];
total_tat += tat[i];
}

printf("SJF Scheduling:\n");
printf("Average Waiting Time: %.2f\n", total_wt / n);
printf("Average Turnaround Time: %.2f\n", total_tat / n);
}

int main() {
int processes[] = {1, 2, 3, 4};
int n = sizeof(processes) / sizeof(processes[0]);
int burst_time[] = {6, 8, 7, 3};

9
findAvgTime(processes, n, burst_time);

return 0;
}

OUTPUT:

SJF Scheduling:
Average Waiting Time: 417.00
Average Turnaround Time: 423.00

ii) Round Robin

#include <stdio.h>

void findWaitingTime(int processes[], int n, int bt[], int quantum, int wt[]) {
int remaining_time[n];
for (int i = 0; i < n; i++) {
remaining_time[i] = bt[i];
wt[i] = 0;
}

int t = 0; // Current time


while (1) {
int done = 1;
for (int i = 0; i < n; i++) {
if (remaining_time[i] > 0) {
done = 0; // There is a pending process
if (remaining_time[i] > quantum) {
t += quantum;
remaining_time[i] -= quantum;
} else {
t += remaining_time[i];
wt[i] = t - bt[i];
remaining_time[i] = 0;
}
}
}
if (done == 1) {
break; // All processes are done
}
}
}

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

10
}
}

void findAvgTime(int processes[], int n, int bt[], int quantum) {


int wt[n], tat[n];
findWaitingTime(processes, n, bt, quantum, wt);
findTurnAroundTime(processes, n, bt, wt, tat);

float total_wt = 0, total_tat = 0;


for (int i = 0; i < n; i++) {
total_wt += wt[i];
total_tat += tat[i];
}

printf("Round Robin Scheduling (Quantum Time = %d):\n", quantum);


printf("Average Waiting Time: %.2f\n", total_wt / n);
printf("Average Turnaround Time: %.2f\n", total_tat / n);
}

int main() {
int processes[] = {1, 2, 3, 4};
int n = sizeof(processes) / sizeof(processes[0]);
int burst_time[] = {10, 5, 8, 12};
int quantum = 2; // Quantum time (time slice)

findAvgTime(processes, n, burst_time, quantum);

return 0;
}

OUTPUT:

Round Robin Scheduling (Quantum Time = 2):


Average Waiting Time: 19.25
Average Turnaround Time: 28.00

iii) Priority

#include <stdio.h>

void findWaitingTime(int processes[], int n, int bt[], int priority[], int wt[]) {
int pos, temp;
for (int i = 0; i < n; i++) {
pos = i;
for (int j = i + 1; j < n; j++) {
if (priority[j] < priority[pos]) {
pos = j;
}
}

11
// Swap priority values
temp = priority[i];
priority[i] = priority[pos];
priority[pos] = temp;

// Swap process IDs


temp = processes[i];
processes[i] = processes[pos];
processes[pos] = temp;

// Swap burst times


temp = bt[i];
bt[i] = bt[pos];
bt[pos] = temp;
}

wt[0] = 0;
for (int i = 1; i < n; i++) {
wt[i] = bt[i - 1] + wt[i - 1];
}
}

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

void findAvgTime(int processes[], int n, int bt[], int priority[]) {


int wt[n], tat[n];
findWaitingTime(processes, n, bt, priority, wt);
findTurnAroundTime(processes, n, bt, wt, tat);

float total_wt = 0, total_tat = 0;


for (int i = 0; i < n; i++) {
total_wt += wt[i];
total_tat += tat[i];
}

printf("Priority Scheduling:\n");
printf("Average Waiting Time: %.2f\n", total_wt / n);
printf("Average Turnaround Time: %.2f\n", total_tat / n);
}

int main() {
int processes[] = {1, 2, 3, 4};
int n = sizeof(processes) / sizeof(processes[0]);
int burst_time[] = {6, 8, 7, 3};
int priority[] = {3, 2, 1, 4}; // Lower values indicate higher priority

12
findAvgTime(processes, n, burst_time, priority);

return 0;
}
OUTPUT:

Priority Scheduling:
Average Waiting Time: 10.75
Average Turnaround Time: 16.75

RESULT: The scheduling algorithm has been implemented in C.

EX.NO:3 IMPLEMENTATION OF PRODUCER-CONSUMER PROBLEM USING


SEMAPHORES.

AIM: To Develop a C program to simulate producer-consumer problem using semaphores.

DESCRIPTION:

PROGRAM

13
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

#define BUFFER_SIZE 5

sem_t mutex, fullSlots, emptySlots;


int buffer[BUFFER_SIZE];
int in = 0, out = 0;

void *producer(void *arg)


{
int item = 1;
while (1)
{
sem_wait(&emptySlots);
sem_wait(&mutex);
buffer[in] = item;
printf("Produced item: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
item++;

sem_post(&mutex);
sem_post(&fullSlots);
sleep(rand() % 2); // Producer sleeps for random time before producing the next item
}
}

void *consumer(void *arg)


{
while (1)
{
sem_wait(&fullSlots);
sem_wait(&mutex);
int item = buffer[out];
printf("Consumed item: %d\n", item);
out = (out + 1) % BUFFER_SIZE;

sem_post(&mutex);
sem_post(&emptySlots);
sleep(rand() % 2); // Consumer sleeps for random time before consuming the next item
}
}

int main()
{
pthread_t producerThread, consumerThread;

14
// Initialize semaphores
sem_init(&mutex, 0, 1);
sem_init(&fullSlots, 0, 0);
sem_init(&emptySlots, 0, BUFFER_SIZE);

// Create producer and consumer threads


pthread_create(&producerThread, NULL, producer, NULL);
pthread_create(&consumerThread, NULL, consumer, NULL);

// Let the threads run for a while


sleep(10);

// Exit
sem_destroy(&mutex);
sem_destroy(&fullSlots);
sem_destroy(&emptySlots);

return 0;
}

OUTPUT :

Produced item: 1
Consumed item: 1
Produced item: 2
Consumed item: 2
Produced item: 3
Consumed item: 3
Produced item: 4
Consumed item: 4
Produced item: 5
Consumed item: 5
Produced item: 6
Consumed item: 6
Produced item: 7
Produced item: 8
Consumed item: 7
Produced item: 9
Produced item: 10
Produced item: 11
Produced item: 12
Consumed item: 8
Produced item: 13
Consumed item: 9
Consumed item: 10
Produced item: 14
Consumed item: 11

15
Consumed item: 12
Consumed item: 13
Consumed item: 14
Produced item: 15
Consumed item: 15
Produced item: 16
Consumed item: 16

RESULT:

EX.NO.4: IMPLEMENTATION OF INTERPROCESS COMMUNICATION


BETWEEN A READER PROCESS AND A WRITER PROCESS

AIM: Develop a C program which demonstrates interprocess communication between a reader


process and a writer process. Use mkfifo, open, read, write and close APIs in your program.

DESRIPTION:

PROGRAM:

i. writer.c (Writer Process)


#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
char *fifoFile = "myfifo";

16
mkfifo(fifoFile, 0666);

int fd = open(fifoFile, O_WRONLY);


if (fd == -1) {
perror("Error opening FIFO");
exit(EXIT_FAILURE);
}

char message[] = "Hello, Reader!";


write(fd, message, sizeof(message));
close(fd);

printf("Message sent to the reader: %s\n", message);

return 0;
}

ii. reader.c (Reader Process)

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
char *fifoFile = "myfifo";
mkfifo(fifoFile, 0666);

int fd = open(fifoFile, O_RDONLY);


if (fd == -1) {
perror("Error opening FIFO");
exit(EXIT_FAILURE);
}

char message[100];
read(fd, message, sizeof(message));
printf("Message received from the writer: %s\n", message);
close(fd);
return 0;
}

OUTPUT :

17
Writer:
Message sent to the reader: Hello, Reader!

Reader:
Message received from the writer: Hello, Reader!

RESULT:

EX.NO.5: IMPLEMENTATION OF BANKERS ALGORITHM FOR DEADLOCK


AVOIDANCE

AIM: Develop a C program to simulate Bankers Algorithm for DeadLock Avoidance.

DESRIPTION:

PROGRAM:

18
#include <stdio.h>

int main() {
int processes, resources, i, j, k;

// Input the number of processes and resources


printf("Enter number of processes: ");
scanf("%d", &processes);
printf("Enter number of resources: ");
scanf("%d", &resources);

int max[processes][resources]; // Maximum resources that can be allocated to processes


int allocated[processes][resources]; // Resources currently allocated to processes
int available[resources]; // Available resources
int need[processes][resources]; // Resources needed by processes
int work[resources];

// Input maximum resources that can be allocated to processes


printf("Enter maximum resources for each process:\n");
for (i = 0; i < processes; i++) {
printf("Process %d: ", i);
for (j = 0; j < resources; j++) {
scanf("%d", &max[i][j]);
}
}

// Input resources currently allocated to processes


printf("Enter resources currently allocated to each process:\n");
for (i = 0; i < processes; i++) {
printf("Process %d: ", i);
for (j = 0; j < resources; j++) {
scanf("%d", &allocated[i][j]);
}
}

// Input available resources


printf("Enter available resources: ");
for (i = 0; i < resources; i++) {
scanf("%d", &available[i]);
}

// Calculate resources needed by processes


for (i = 0; i < processes; i++) {
for (j = 0; j < resources; j++) {
need[i][j] = max[i][j] - allocated[i][j];
}
}

19
// Initialize work to available resources
for (i = 0; i < resources; i++)
{
work[i] = available[i];
}

// Safety algorithm to check if system is in safe state


int finish[processes];
for (i = 0; i < processes; i++)
{
finish[i] = 0;
}
int safeSequence[processes];
int count = 0;
while (count < processes)
{
int found = 0;
for (i = 0; i < processes; i++)
{
if (finish[i] == 0) {
int canBeAllocated = 1;
for (j = 0; j < resources; j++)
{
if (need[i][j] > work[j])
{
canBeAllocated = 0;
break;
}
}
if (canBeAllocated) {
for (k = 0; k < resources; k++) {
work[k] += allocated[i][k];
}
safeSequence[count++] = i;
finish[i] = 1;
found = 1;
}
}
}
// If no process can be allocated, the system is in unsafe state
if (!found) {
printf("System is in unsafe state, cannot allocate resources.\n");
return 0;
}
}
// If the system is in a safe state, print the safe sequence
printf("Safe Sequence: ");
for (i = 0; i < processes; i++) {
printf("%d ", safeSequence[i]);
}

20
printf("\n");

return 0;
}

OUTPUT :

Enter number of processes: 2


Enter number of resources: 2
Enter maximum resources for each process:
Process 0: 4 5
Process 1: 2 4
Enter resources currently allocated to each process:
Process 0: 1 1
Process 1: 2 1
Enter available resources: 5 6
Safe Sequence: 0 1

RESULT:

21
EX.NO.6: IMPLEMENTATION OF CONTIGUOUS MEMORY ALLOCATION
TECHNIQUES

AIM: Develop a C program to simulate the following contiguous memory allocation Techniques:
a) Worst fit b) Best fit c) First fit.

DESRIPTION:

PROGRAM:

i) Contiguous Memory Allocation - Worst Fit


#include <stdio.h>

void worstFit(int blockSize[], int m, int processSize[], int n) {


int allocation[n];
for (int i = 0; i < n; i++) {
allocation[i] = -1;
}

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


int wstIdx = -1;
for (int j = 0; j < m; j++) {
if (blockSize[j] >= processSize[i]) {
if (wstIdx == -1 || blockSize[j] > blockSize[wstIdx]) {
wstIdx = j;
}
}
}

if (wstIdx != -1) {
allocation[i] = wstIdx;
blockSize[wstIdx] -= processSize[i];
}
}

22
printf("Worst Fit Allocation:\n");
for (int i = 0; i < n; i++) {
if (allocation[i] != -1) {
printf("Process %d allocated to Block %d\n", i, allocation[i]);
} else {
printf("Process %d cannot be allocated\n", i);
}
}
}

int main() {
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);

worstFit(blockSize, m, processSize, n);

return 0;
}

OUTPUT :

Worst Fit Allocation:


Process 0 allocated to Block 4
Process 1 allocated to Block 1
Process 2 allocated to Block 4
Process 3 cannot be allocated

ii) Contiguous Memory Allocation – Best Fit

#include <stdio.h>
#include <limits.h>

void bestFit(int blockSize[], int m, int processSize[], int n) {


int allocation[n];
for (int i = 0; i < n; i++) {
allocation[i] = -1;
}

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


int bestIdx = -1;
for (int j = 0; j < m; j++) {
if (blockSize[j] >= processSize[i]) {

23
if (bestIdx == -1 || blockSize[j] < blockSize[bestIdx]) {
bestIdx = j;
}
}
}

if (bestIdx != -1) {
allocation[i] = bestIdx;
blockSize[bestIdx] -= processSize[i];
}
}

printf("Best Fit Allocation:\n");


for (int i = 0; i < n; i++) {
if (allocation[i] != -1) {
printf("Process %d allocated to Block %d\n", i, allocation[i]);
} else {
printf("Process %d cannot be allocated\n", i);
}
}
}

int main() {
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);

bestFit(blockSize, m, processSize, n);

return 0;
}

OUTPUT :

Best Fit Allocation:


Process 0 allocated to Block 3
Process 1 allocated to Block 1
Process 2 allocated to Block 2
Process 3 allocated to Block 4

iii) Contiguous Memory Allocation –First Fit

24
#include <stdio.h>

void firstFit(int blockSize[], int m, int processSize[], int n)


{
int allocation[n];
for (int i = 0; i < n; i++)
{
allocation[i] = -1;
}

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


for (int j = 0; j < m; j++) {
if (blockSize[j] >= processSize[i])
{
allocation[i] = j;
blockSize[j] -= processSize[i];
break;
}
}
}

printf("First Fit Allocation:\n");


for (int i = 0; i < n; i++) {
if (allocation[i] != -1) {
printf("Process %d allocated to Block %d\n", i, allocation[i]);
} else {
printf("Process %d cannot be allocated\n", i);
}
}
}

int main() {
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);

firstFit(blockSize, m, processSize, n);


return 0;
}

OUTPUT :

First Fit Allocation:


Process 0 allocated to Block 1
Process 1 allocated to Block 4
Process 2 allocated to Block 1
Process 3 cannot be allocated

25
RESULT:

EX.NO.7: IMPLEMENTATION OF PAGE REPLACEMENT ALGORITHMS


AIM: Develop a C program to simulate page replacement algorithms: a) FIFO b) LRU

DESRIPTION:

26
PROGRAM:

i) Page Replacement Algorithm - FIFO (First-In-First-Out)

#include <stdio.h>

void FIFO(int pages[], int n, int capacity) {


int frame[capacity];
int frameIndex = 0;
int pageFaults = 0;

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


frame[i] = -1;
}
for (int i = 0; i < n; i++) {
int pageFound = 0;
for (int j = 0; j < capacity; j++) {
if (frame[j] == pages[i]) {
pageFound = 1;
break;
}
}

if (!pageFound) {
frame[frameIndex] = pages[i];
frameIndex = (frameIndex + 1) % capacity;
pageFaults++;
}

printf("Page %d -> Frame: ", pages[i]);


for (int j = 0; j < capacity; j++) {
if (frame[j] != -1) {
printf("%d ", frame[j]);
} else {
printf("- ");
}
}
printf("\n");
}

printf("Total Page Faults: %d\n", pageFaults);


}

int main() {
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
int n = sizeof(pages) / sizeof(pages[0]);
int capacity = 3; // Number of frames
FIFO(pages, n, capacity);
return 0;
}

27
Output:

Page 7 -> Frame: 7 - -


Page 0 -> Frame: 7 0 -
Page 1 -> Frame: 7 0 1
Page 2 -> Frame: 2 0 1
Page 0 -> Frame: 2 0 1
Page 3 -> Frame: 2 3 1
Page 0 -> Frame: 2 3 0
Page 4 -> Frame: 4 3 0
Page 2 -> Frame: 4 2 0
Page 3 -> Frame: 4 2 3
Page 0 -> Frame: 0 2 3
Page 3 -> Frame: 0 2 3
Page 2 -> Frame: 0 2 3
Total Page Faults: 10

ii) Page Replacement Algorithm - LRU (Least Recently Used)

#include <stdio.h>
#include <limits.h>

void LRU(int pages[], int n, int capacity) {


int frame[capacity];
int frameIndex = 0;
int pageFaults = 0;
int pageLastUsed[n];
for (int i = 0; i < n; i++) {
pageLastUsed[i] = -1;
}

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


int pageFound = 0;
for (int j = 0; j < capacity; j++) {
if (frame[j] == pages[i]) {
pageFound = 1;
pageLastUsed[pages[i]] = i;
break;
}
}

if (!pageFound) {
int lruIndex = INT_MAX;
int replaceIndex = -1;
for (int j = 0; j < capacity; j++) {
if (pageLastUsed[frame[j]] < lruIndex) {
lruIndex = pageLastUsed[frame[j]];
replaceIndex = j;
}

28
}
frame[replaceIndex] = pages[i];
pageLastUsed[pages[i]] = i;
pageFaults++;
}

printf("Page %d -> Frame: ", pages[i]);


for (int j = 0; j < capacity; j++) {
if (frame[j] != -1) {
printf("%d ", frame[j]);
} else {
printf("- ");
}
}
printf("\n");
}

printf("Total Page Faults: %d\n", pageFaults);


}

int main() {
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
int n = sizeof(pages) / sizeof(pages[0]);
int capacity = 3; // Number of frames
LRU (pages, n, capacity);
return 0;
}

OUTPUT :

Page 7 -> Frame: 7 0 0


Page 0 -> Frame: 7 0 0
Page 1 -> Frame: 1 0 0
Page 2 -> Frame: 1 2 0
Page 0 -> Frame: 1 2 0
Page 3 -> Frame: 3 2 0
Page 0 -> Frame: 3 2 0
Page 4 -> Frame: 3 4 0
Page 2 -> Frame: 2 4 0
Page 3 -> Frame: 2 4 3
Page 0 -> Frame: 2 0 3
Page 3 -> Frame: 2 0 3
Page 2 -> Frame: 2 0 3
Total Page Faults: 8

29
RESULT:

EX.NO.8: IMPLEMENTATION OF FILE ORGANIZATION TECHNIQUES

AIM: To Develop a C program to Simulate following File Organization Techniques


a) Single level directory b) Two level directory

DESRIPTION:

PROGRAM:

i) Single level directory


#include <stdio.h>

30
#include <string.h>

struct File {
char name[50];
};

struct File singleLevelDirectory[100];


int singleLevelFileCount = 0;

void createFileSingleLevel(char name[]) {


strcpy(singleLevelDirectory[singleLevelFileCount].name, name);
singleLevelFileCount++;
}

void displaySingleLevelDirectory() {
printf("Single Level Directory:\n");
for (int i = 0; i < singleLevelFileCount; ++i) {
printf("- %s\n", singleLevelDirectory[i].name);
}
}

int main() {
createFileSingleLevel("file1.txt");
createFileSingleLevel("document.docx");
createFileSingleLevel("image.jpg");
createFileSingleLevel("data.csv");

displaySingleLevelDirectory();

return 0;
}

OUTPUT :

Single Level Directory:


- file1.txt
- document.docx
- image.jpg
- data.csv

ii) Two level directory


#include <stdio.h>
#include <string.h>

struct File {

31
char name[50];
};

struct UserDirectory {
char username[50];
struct File files[100];
int fileCount;
};

struct UserDirectory twoLevelDirectory[100];


int userCount = 0;

void createFileTwoLevel(char username[], char filename[]) {


int found = 0;
for (int i = 0; i < userCount; ++i) {
if (strcmp(twoLevelDirectory[i].username, username) == 0) {
strcpy(twoLevelDirectory[i].files[twoLevelDirectory[i].fileCount].name, filename);
twoLevelDirectory[i].fileCount++;
found = 1;
break;
}
}
if (!found) {
strcpy(twoLevelDirectory[userCount].username, username);
strcpy(twoLevelDirectory[userCount].files[0].name, filename);
twoLevelDirectory[userCount].fileCount = 1;
userCount++;
}
}

void displayTwoLevelDirectory() {
printf("Two Level Directory:\n");
for (int i = 0; i < userCount; ++i) {
printf("%s:\n", twoLevelDirectory[i].username);
for (int j = 0; j < twoLevelDirectory[i].fileCount; ++j) {
printf("- %s\n", twoLevelDirectory[i].files[j].name);
}
}
}

int main() {
createFileTwoLevel("User1", "file1.txt");
createFileTwoLevel("User1", "document1.docx");
createFileTwoLevel("User2", "image.jpg");
createFileTwoLevel("User2", "data.csv");

displayTwoLevelDirectory();
return 0;
}

OUTPUT :

32
Two Level Directory:
User1:
- file1.txt
- document1.docx
User2:
- image.jpg
- data.csv

RESULT:

33
EX.NO.9: IMPLEMENTATION OF LINKED FILE ALLOCATION STRATEGIES.

AIM: To Develop a C program to simulate the Linked file allocation strategies.

DESRIPTION:

PROGRAM:

#include <stdio.h>
#include <stdlib.h>

struct Block {
int data;
struct Block* next;
};

void displayBlocks(struct Block* start) {


struct Block* temp = start;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

void addBlock(struct Block** start, int data) {


struct Block* newBlock = (struct Block*)malloc(sizeof(struct Block));
newBlock->data = data;
newBlock->next = NULL;

if (*start == NULL) {
*start = newBlock;
} else {
struct Block* temp = *start;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newBlock;

34
}
}

int main() {
struct Block* start = NULL;

printf("Linked File Allocation Simulation:\n");

// Adding blocks to the linked list


addBlock(&start, 1);
addBlock(&start, 2);
addBlock(&start, 3);
addBlock(&start, 4);

// Displaying the blocks


printf("Linked List Blocks:\n");
displayBlocks(start);

// Freeing allocated memory


struct Block* temp;
while (start != NULL) {
temp = start;
start = start->next;
free(temp);
}

return 0;
}

OUTPUT :

Linked File Allocation Simulation:


Linked List Blocks:
1 -> 2 -> 3 -> 4 -> NULL

RESULT:

35
EX.NO.10: IMPLEMENTATION OF SCAN DISK SCHEDULING
ALGORITHM

AIM: To Develop a C program to simulate SCAN disk scheduling algorithm.


.
DESRIPTION:

PROGRAM:

#include <stdio.h>
#include <stdlib.h>

int main() {
int queue[20], seekSequence[20], head, size, totalSeekSequence = 0;
int left = 0, right = 199, distance, temp, i, j;

printf("Enter the size of the disk queue: ");


scanf("%d", &size);

printf("Enter the disk queue (requests): ");


for (i = 0; i < size; i++) {
scanf("%d", &queue[i]);
}

printf("Enter the initial head position: ");


scanf("%d", &head);

// Sort the disk queue in ascending order

36
for (i = 0; i < size - 1; i++) {
for (j = i + 1; j < size; j++) {
if (queue[i] > queue[j]) {
temp = queue[i];
queue[i] = queue[j];
queue[j] = temp;
}
}
}

// SCAN algorithm simulation


for (i = 0; i < size; i++) {
if (queue[i] >= head) {
left = i - 1;
right = i;
break;
}
}

// Calculate seek sequence


for (i = 0; i < size; i++) {
if (left >= 0) {
seekSequence[i] = queue[left];
left--;
} else {
seekSequence[i] = queue[right];
right++;
}
}

// Calculate total seek sequence and display


for (i = 0; i < size; i++) {
distance = abs(seekSequence[i] - head);
totalSeekSequence += distance;
head = seekSequence[i];
printf("%d -> ", seekSequence[i]);
}

printf("NULL\n");
printf("Total seek sequence length: %d\n", totalSeekSequence);

return 0;
}

OUTPUT :

Enter the size of the disk queue: 4


Enter the disk queue (requests): 2

37
3
5
3
Enter the initial head position: 1
2 -> 3 -> 3 -> 5 -> NULL
Total seek sequence length: 4

RESULT:

38

You might also like