0% found this document useful (0 votes)
22 views33 pages

OS Lab Manual

Uploaded by

architha1105
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)
22 views33 pages

OS Lab Manual

Uploaded by

architha1105
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/ 33

DEPARTMENT OF ARTIFICIAL INTELLIGENCE & MACHINE LEARNING

THE OXFORD COLLEGE ENGINEERING

Hosur Road, Bommanahalli, Bengaluru-560 068

Website:www.theoxford.edu/http://theoxfordengg.org/Email :[email protected]
APPROVED BY AICTE, ACCREDITED BY NAAC, AFFILIATED TO VTU

LAB MANUAL FOR

OPERATING SYSTEMS

BCS303

1
Vision of the Institute:
“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 of the Institute:


Our Mission is to develop Competent Students with good value Systems and Face
Challenges of the Continuously Changing World.

Vision of the Department:


“To Create Technocrats with Cognitive Skills and Technical Proficiency to Succeed in the
Challenging World of New Era”.

Mission of the Department:


To Produce outstanding Artificial Engineering Professionals with cognitive
MD1 skills.

To Enrich the students’ skill set by continuous learning and research


MD2
capabilities with vibrant ambience.
● To empower students with Technical Proficiency, Competency and
MD3 Ethicalness for the new Era.

Program Educational Objectives (PEOs)

To Empower graduates with cognitive skills to lead their professional career in


Reputed Industries and Solve Problems by Applying the Principles of Mathematics,
PEO 1 Artificial Intelligence and Machine Learning, Scientific Investigations using the
Latest Technologies through the opportunities of Artificial Intelligence & Machine
Learning.
To Enrich the graduates by engaging them in research area of Artificial
PEO 2 Intelligence & Machine Learning and empower them to work in scientific
environment.
To create graduates with Professional Advancement, Communication Skills, Life
PEO 3 Long Learning Process, Ethical Attitude, Social Responsibility, Team Work,
Project Management and Leadership Skills Through Continuing Education.

Program Specific Outcomes (PSOs)


Use appropriate Techniques and Tools in application design with a knowledge of
Computer Science, Networking, Software Engineering, Programs, Projects, Design
PSO 1
of new Algorithms, Artificial Intelligence and Machine Learning Systems for
Solving Complex Engineering Problems.
Inculcate the ability to work with Professional Ethics, Communication Skills,
PSO 2 Team Work, Exchange of Innovative Ideas to Carryout Lifelong Learning with the
state of art technologies and development.

2
PROGRAM OUTCOMES

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

3
INDEX

S. No. PROGRAME NAME PAGE No.

1 Develop a c program to implement the Process system calls (fork (), exec(), 5
wait(), create process, terminate process)

2 Simulate the following CPU scheduling algorithms to find turnaround time 7


and waiting time a) FCFS
a)FCFS b) SJF c) Round Robin d) Priority.

3 Develop a C program to simulate producer-consumer problem using 13


semaphores.

4 Develop a C program which demonstrates interprocess communication 15


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 17
Avoidance.

6 Develop a C program to simulate the following contiguous memory 20


allocation Techniques:
a) Worst fit b) Best fit c) First fit.

7 Develop a C program to simulate page replacement algorithms: 24


a) FIFO b) LRU
8 Simulate following File Organization Techniques 27
a) Single level directory b) Two level directory
9 Develop a C program to simulate the Linked file allocation strategies. 30
10 Design and develop a program in C that uses Hash function H:K->L as 32
H(K)=K mod m ( reminder method) and implement hashing technique to
map a given key K to the address space L. Resolve the collision ( if any)
using linear probing.

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)) {
printf("Child process terminated with status: %d\n", WEXITSTATUS(status));
} else {
printf("Child process terminated abnormally\n");

5
}
}
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.

PROGRAM a)
#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");
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:

7
Average Waiting Time: 8.33
Average Turnaround Time: 16.0

b)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) {
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];
8
}
}

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

findAvgTime(processes, n, burst_time);

return 0;
}

OUTPUT:
SJF Scheduling:
Average Waiting Time: 2.50
Average Turnaround Time: 8.5

c)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;
9
} 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];
}
}

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

d) Priority

#include <stdio.h>
10
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;
}
}

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

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.

PROGRAM

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
12
#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;

// 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);
13
// 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
Produced item: 5
Produced item: 6
Consumed item: 4
Produced item: 7
Produced item: 8
Consumed item: 5
Produced item: 9
Consumed item: 6
Produced item: 10
Produced item: 11
Consumed item: 7
Produced item: 12
Consumed item: 8
Produced item: 13
Consumed item: 9
Consumed item: 10
Produced item: 14
Consumed item: 11
Consumed item: 12
Consumed item: 13
Consumed item: 14
Produced item: 15
Consumed item: 15
Produced item: 16
Consumed item: 16
Produced item: 17
Consumed item: 17
Produced item: 18
Consumed item: 18

RESULT:

14
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.

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

15
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 :

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:

16
#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];
}
}

// Initialize work to available resources


for (i = 0; i < resources; i++)
{
work[i] = available[i];
17
}

// 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]);
}
printf("\n");

return 0;
}

OUTPUT :
Enter number of processes: 3
Enter number of resources: 4
18
Enter maximum resources for each process:
Process 0: 2
3
4
5
Process 1:
1
2
3
4
Process 2: 2
4
4
5
Enter resources currently allocated to each process:
Process 0: 3

2
4
5
Process 1: 2
1
3
4
Process 2: 4
4
5
2
Enter available resources: 2
3
4
1
Safe Sequence: 0 1 2

RESULT:

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.

PROGRAM:

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

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
20
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]) {
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
21
Process 1 allocated to Block 1
Process 2 allocated to Block 2
Process 3 allocated to Block 4

iii) Contiguous Memory Allocation –First Fit

#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
22
RESULT:

EX.NO.7: IMPLEMENTATION OF PAGE REPLACEMENT ALGORITHMS


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

PROGRAM:

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

#include <stdio.h>

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


int frame[capacity];
23
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;
}
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
24
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;
}
}
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);


25
}

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

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

PROGRAM:

i) Single level directory

26
#include <stdio.h>
#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 {
char name[50];
};

struct UserDirectory {
27
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 :
Two Level Directory:
User1:
- file1.txt
- document1.docx
User2:
- image.jpg
- data.csv
28
RESULT:

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

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

PROGRAM:

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

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

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

OUTPUT :
Linked File Allocation Simulation:
Linked List Blocks:
1 -> 2 -> 3 -> 4 -> NULL

RESULT:

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

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


.
PROGRAM:

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

int main() {

31
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


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

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

return 0;
}

OUTPUT :
Enter the size of the disk queue: 3
Enter the disk queue (requests): 5
3
4
Enter the initial head position: 3
3 -> 4 -> 5 -> NULL
Total seek sequence length: 2

RESULT:

33

You might also like