UPDATED OS LAB MANUAL 2025
UPDATED OS LAB MANUAL 2025
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING (CSD&CSC)
1
INDEX
2 Write programs using the I/O system calls of UNIX/LINUX operating 11-15
system (open, read, write, close, fcntl, seek, stat, opendir, readdir)
2
1. Write C programs to simulate the following CPU Scheduling algorithms
a) FCFS b) SJF c) Round Robin d) priority
a) FCFS Algorithm
1. Input number of processes n.
2. Input burst time for each process.
3. Set waiting time of first process to 0:
WT[0] = 0
4. For each process i from 1 to n-1:
WT[i] = WT[i-1] + BT[i-1]
5. For each process i:
TAT[i] = WT[i] + BT[i]
6. Display Burst Time, Waiting Time, and Turnaround Time.
7. Calculate averages:
o Average Waiting Time = total WT / n
o Average Turnaround Time = total TAT / n
PROGRAM:
#include <stdio.h>
int main() {
int n, i;
int burst_time[20], waiting_time[20], turnaround_time[20];
int total_waiting_time = 0, total_turnaround_time = 0;
// Input number of processes
printf("Enter number of processes: ");
scanf("%d", &n);
// Input burst time for each process
printf("Enter burst time for each process:\n");
for(i = 0; i < n; i++) {
printf("P[%d]: ", i+1);
scanf("%d", &burst_time[i]);
}
// First process has 0 waiting time
waiting_time[0] = 0;
// Calculate waiting time for each process
for(i = 1; i < n; i++) {
waiting_time[i] = waiting_time[i-1] + burst_time[i-1];
}
// Calculate turnaround time for each process
for(i = 0; i < n; i++) {
turnaround_time[i] = waiting_time[i] + burst_time[i];
3
}
// Display results
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for(i = 0; i < n; i++) {
printf("P[%d]\t%d\t\t%d\t\t%d\n", i+1, burst_time[i], waiting_time[i],
turnaround_time[i]);
total_waiting_time += waiting_time[i];
total_turnaround_time += turnaround_time[i];
}
// Display averages
printf("\nAverage Waiting Time: %.2f", (float)total_waiting_time / n);
printf("\nAverage Turnaround Time: %.2f\n", (float)total_turnaround_time / n);
return 0;
}
Sample Output:
Enter number of processes: 3
Enter burst time for each process:
P[1]: 5
P[2]: 8
P[3]: 12
Process Burst Time Waiting Time Turnaround Time
P[1] 5 0 5
P[2] 8 5 13
P[3] 12 13 25
Average Waiting Time: 6.00
Average Turnaround Time: 14.33
4
B) SJF Algorithm
1. Input number of processes.
2. Input burst time for each process.
3. Sort processes by burst time (Shortest first).
4. Set waiting time of first process to 0.
5. Calculate waiting time for other processes:
o WT[i] = WT[i-1] + BT[i-1]
6. Calculate turnaround time:
o TAT[i] = WT[i] + BT[i]
7. Display all times and compute averages.
PROGRAM:
#include <stdio.h>
int main() {
int n, i, j;
int bt[20], p[20], wt[20], tat[20], temp;
float total_wt = 0, total_tat = 0;
// Input number of processes
printf("Enter number of processes: ");
scanf("%d", &n);
// Input burst times and process IDs
printf("Enter burst time for each process:\n");
for (i = 0; i < n; i++) {
printf("P[%d]: ", i + 1);
scanf("%d", &bt[i]);
p[i] = i + 1; // Process ID
}
// Sort processes by burst time using simple bubble sort
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (bt[i] > bt[j]) {
// Swap burst time
temp = bt[i];
bt[i] = bt[j];
bt[j] = temp;
// Swap process ID
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
5
// Waiting time for first process is 0
wt[0] = 0;
// Calculate waiting time
for (i = 1; i < n; i++) {
wt[i] = wt[i - 1] + bt[i - 1];
}
// Calculate turnaround time
for (i = 0; i < n; i++) {
tat[i] = wt[i] + bt[i];
total_wt += wt[i];
total_tat += tat[i];
}
// Print results
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("P[%d]\t%d\t\t%d\t\t%d\n", p[i], bt[i], wt[i], tat[i]);
}
// Average times
printf("\nAverage Waiting Time: %.2f", total_wt / n);
printf("\nAverage Turnaround Time: %.2f\n", total_tat / n);
return 0;
}
Sample Output:
Enter number of processes: 4
Enter burst time for each process:
P[1]: 6
P[2]: 8
P[3]: 7
P[4]: 3
Process Burst Time Waiting Time Turnaround Time
P[4] 3 0 3
P[1] 6 3 9
P[3] 7 9 16
P[2] 8 16 24
Average Waiting Time: 7.00
Average Turnaround Time: 13.00
6
C) PRIORITY Algorithm
1. Input number of processes.
2. Input burst time and priority for each process.
3. Sort processes based on priority (lower number = higher priority).
4. Set waiting time of first process to 0.
5. Calculate waiting time for each process:
o WT[i] = WT[i-1] + BT[i-1]
6. Calculate turnaround time:
o TAT[i] = WT[i] + BT[i]
7. Display all times and compute average waiting and turnaround time.
PROGRAM:
#include <stdio.h>
int main() {
int n, i, j;
int bt[20], p[20], wt[20], tat[20], pr[20], temp;
float total_wt = 0, total_tat = 0;
// Input number of processes
printf("Enter number of processes: ");
scanf("%d", &n);
// Input burst time and priority
printf("Enter burst time and priority for each process:\n");
for (i = 0; i < n; i++) {
printf("P[%d] Burst Time: ", i+1);
scanf("%d", &bt[i]);
printf("P[%d] Priority (Lower number = Higher priority): ", i+1);
scanf("%d", &pr[i]);
p[i] = i + 1; // Process ID
}
// Sort processes by priority (ascending)
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (pr[i] > pr[j]) {
// Swap priority
temp = pr[i];
pr[i] = pr[j];
pr[j] = temp;
// Swap burst time
temp = bt[i];
bt[i] = bt[j];
bt[j] = temp;
// Swap process ID
7
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
// First process waiting time is 0
wt[0] = 0;
// Calculate waiting times
for (i = 1; i < n; i++) {
wt[i] = wt[i-1] + bt[i-1];
}
// Calculate turnaround times
for (i = 0; i < n; i++) {
tat[i] = wt[i] + bt[i];
total_wt += wt[i];
total_tat += tat[i];
}
// Print results
printf("\nProcess\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("P[%d]\t%d\t\t%d\t\t%d\t\t%d\n", p[i], bt[i], pr[i], wt[i], tat[i]);
}
// Print averages
printf("\nAverage Waiting Time: %.2f", total_wt / n);
printf("\nAverage Turnaround Time: %.2f\n", total_tat / n);
return 0;
}
Sample Output:
Enter number of processes: 3
Enter burst time and priority for each process:
P[1] Burst Time: 10
P[1] Priority (Lower number = Higher priority): 2
P[2] Burst Time: 5
P[2] Priority: 1
P[3] Burst Time: 8
P[3] Priority: 3
Process Burst Time Priority Waiting Time Turnaround Time
P[2] 5 1 0 5
P[1] 10 2 5 15
P[3] 8 3 15 23
Average Waiting Time: 6.67
8
Average Turnaround Time: 14.33
D) ROUND ROBIN Algorithm
1. Input number of processes.
2. Input arrival time and burst time for each process.
3. Input the time quantum.
4. Initialize remaining time = burst time for all processes.
5. Start looping through processes in order:
o If a process has remaining time and has arrived:
Run it for time quantum or remaining time, whichever is smaller.
Update current time and remaining time.
If process finishes, calculate waiting time and turnaround time.
6. Repeat until all processes are finished.
7. Display turnaround and waiting times.
8. Calculate averages.
PROGRAM:
#include <stdio.h>
int main() {
int i, n, time, remain, flag = 0, tq;
int wt = 0, tat = 0;
int bt[10], rt[10]; // bt = burst time, rt = remaining time
int at[10]; // arrival time
// Input number of processes
printf("Enter number of processes: ");
scanf("%d", &n);
remain = n;
// Input arrival time and burst time
for (i = 0; i < n; i++) {
printf("Enter arrival time and burst time for process P[%d]: ", i + 1);
scanf("%d%d", &at[i], &bt[i]);
rt[i] = bt[i];
}
// Input time quantum
printf("Enter time quantum: ");
scanf("%d", &tq);
printf("\nProcess\tTurnaround Time\tWaiting Time\n");
for (time = 0, i = 0; remain != 0;) {
if (rt[i] > 0 && at[i] <= time) {
if (rt[i] <= tq) {
time += rt[i];
rt[i] = 0;
flag = 1;
} else {
rt[i] -= tq;
9
time += tq;
}
if (rt[i] == 0 && flag == 1) {
remain--;
printf("P[%d]\t%d\t\t%d\n", i + 1, time - at[i], time - at[i] - bt[i]);
wt += time - at[i] - bt[i];
tat += time - at[i];
flag = 0;
}
}
// Round robin logic: move to next process
i = (i + 1) % n;
}
printf("\nAverage Waiting Time: %.2f\n", (float)wt / n);
printf("Average Turnaround Time: %.2f\n", (float)tat / n);
return 0;
}
Sample Output:
Enter number of processes: 3
Enter arrival time and burst time for process P[1]: 0 5
Enter arrival time and burst time for process P[2]: 1 4
Enter arrival time and burst time for process P[3]: 2 6
Enter time quantum: 2
Process Turnaround Time Waiting Time
P[1] 13 8
P[2] 9 5
P[3] 17 11
Average Waiting Time: 8.00
Average Turnaround Time: 13.00
10
2. Write programs using the I/O system calls of UNIX/LINUX operating system
(open, read, write, close,fcntl, seek, stat, opendir, readdir), open(), read(), write(),
close().
Sample Output:
Program: Copy input.txt to output.txt
Input:Hello, world!
Output:Hello, world!
11
b) Lseek()
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int fd;
char buf[20];
fd = open("input.txt", O_RDONLY);
if (fd < 0) {
perror("open");
return 1;
}
lseek(fd, 5, SEEK_SET); // move 5 bytes from start
read(fd, buf, 10);
buf[10] = '\0';
printf("Read after seek: %s\n", buf);
close(fd);
return 0;
}
Sample Output:
Read specific part of input.txt
Input: ABCDEFGH1234567890
Output: Read after seek: FGHI234567
(seeks 5 bytes ahead, then reads 10 bytes)
12
c) fcntl()
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main() {
int fd = open("input.txt", O_RDONLY);
if (fd < 0) {
perror("open");
return 1;
}
int flags = fcntl(fd, F_GETFL);
if (flags & O_RDONLY)
printf("File is opened in read-only mode.\n");
close(fd);
return 0;
}
Sample Output:
File is opened in read-only mode.
13
d) stat()
#include <sys/stat.h>
#include <stdio.h>
int main() {
struct stat st;
if (stat("input.txt", &st) == 0) {
printf("File size: %ld bytes\n", st.st_size);
printf("Permissions: %o\n", st.st_mode & 0777);
} else {
perror("stat");
}
return 0;
}
Sample Output:
File size: 20 bytes
Permissions: 644
14
e) opendir(), readdir()
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
} else {
perror("opendir");
}
return 0;
}
Sample Output:
Current Directory:
input.txt
output.txt
program.c
Sample Output:
.
..
input.txt
output.txt
program.c
(. and .. are current and parent directory entries)
15
3. Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and
Prevention.
BANKERS ALGORITHM
1. Input number of processes and resource types.
2. Input Allocation, Max, and Available matrices.
3. Calculate Need matrix as:
Need[i][j] = Max[i][j] - Allocation[i][j]
4. Initialize Finish[] to false for all processes.
5. Find a process i such that:
a. Finish[i] == false
b. Need[i] <= Available for all resources.
6. If found:
a. Add its allocation to available.
b. Mark it as finished.
c. Add to safe sequence.
7. Repeat until all processes are finished or no such process exists.
8. If all processes finish, system is in a safe state
PROGRAM:
.
#include <stdio.h>
#include <stdbool.h>
int main() {
int n, m, i, j, k;
int alloc[10][10], max[10][10], need[10][10], avail[10];
int finish[10], safeSeq[10];
printf("Enter number of processes: ");
scanf("%d", &n);
printf("Enter number of resources: ");
scanf("%d", &m);
printf("Enter Allocation matrix:\n");
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
scanf("%d", &alloc[i][j]);
printf("Enter Max matrix:\n");
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
scanf("%d", &max[i][j]);
printf("Enter Available resources:\n");
16
for (i = 0; i < m; i++)
scanf("%d", &avail[i]);
// Calculate Need matrix
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
// Initialize finish array
for (i = 0; i < n; i++)
finish[i] = 0;
int count = 0;
while (count < n) {
bool found = false;
for (i = 0; i < n; i++) {
if (finish[i] == 0) {
bool canExecute = true;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]) {
canExecute = false;
break;
}
}
if (canExecute) {
for (k = 0; k < m; k++)
avail[k] += alloc[i][k];
safeSeq[count++] = i;
finish[i] = 1;
found = true;
}
}
}
if (!found) {
printf("\nSystem is NOT in a safe state.\n");
return 1;
}
}
printf("\nSystem is in a SAFE state.\nSafe sequence: ");
for (i = 0; i < n; i++)
printf("P[%d] ", safeSeq[i]);
printf("\n");
return 0;
}
17
Sample Input / Output:
Enter number of processes: 5
Enter number of resources: 3
Enter Allocation matrix:
010
200
302
211
002
Enter Max matrix:
753
322
902
222
433
Enter Available resources:
332
OUTPUT:
System is in a SAFE state.
Safe sequence: P[1] P[3] P[4] P[0] P[2].
18
4. Write a C program to implement the Producer – Consumer problem using
semaphores using UNIX/LINUX system calls.
Simple Algorithm Steps:
1. Initialize three semaphores:
o empty = Buffer size (initially all slots are empty).
o full = 0 (no items are produced initially).
o mutex = 1 (for mutual exclusion).
2. Producer:
o Wait on the empty semaphore (decrement it).
o Wait on the mutex (enter critical section).
o Produce an item and add it to the buffer.
o Signal (increment) the full semaphore.
o Release the mutex (exit critical section).
3. Consumer:
o Wait on the full semaphore (decrement it).
o Wait on the mutex (enter critical section).
o Consume an item from the buffer.
o Signal (increment) the empty semaphore.
o Release the mutex (exit critical section).
4. The program will continue producing and consuming items concurrently.
PROGRAM:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define MAX_BUFFER_SIZE 5
sem_t empty, full, mutex;
int buffer[MAX_BUFFER_SIZE];
int in = 0, out = 0;
void *producer(void *param) {
int item;
while (1) {
item = rand() % 100; // Produce a random item
sem_wait(&empty); // Wait if buffer is full
sem_wait(&mutex); // Enter critical section
buffer[in] = item;
printf("Produced: %d\n", item);
in = (in + 1) % MAX_BUFFER_SIZE;
sem_post(&mutex); // Exit critical section
19
sem_post(&full); // Signal consumer
sleep(1); // Simulate time to produce an item
}
}
void *consumer(void *param) {
int item;
while (1) {
sem_wait(&full); // Wait if buffer is empty
sem_wait(&mutex); // Enter critical section
item = buffer[out];
printf("Consumed: %d\n", item);
out = (out + 1) % MAX_BUFFER_SIZE;
sem_post(&mutex); // Exit critical section
sem_post(&empty); // Signal producer
sleep(1); // Simulate time to consume an item
}
}
int main() {
pthread_t prod, cons;
// Initialize semaphores
sem_init(&empty, 0, MAX_BUFFER_SIZE); // Buffer size
sem_init(&full, 0, 0); // No items initially
sem_init(&mutex, 0, 1); // Mutex for mutual exclusion
// Create producer and consumer threads
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
// Join threads (optional, as it's an infinite loop)
pthread_join(prod, NULL);
pthread_join(cons, NULL);
// Destroy semaphores
sem_destroy(&empty);
sem_destroy(&full);
sem_destroy(&mutex);
return 0;
}
20
Sample Output:
Compile: gcc -o producer_consumer producer_consumer.c -lpthread
Run: ./producer_consumer
Produced: 72
Produced: 16
Produced: 23
Consumed: 72
Consumed: 16
Produced: 45
Consumed: 23
Produced: 88
Consumed: 45
Consumed: 88
21
5.write c programs to illustrate the following IPC mechanisms
a) pipes,b)FIFO'sc)message queuesd) Shared memory.
Sample Output:
23
o Compile: gcc fifo_writer.c -o fifo_writer and gcc fifo_reader.c -o
fifo_reader
o Run Writer: ./fifo_writer
o Run Reader: ./fifo_reader
Writer Output:
No output, but the message is written to the FIFO
Reader Output:
Reader received message: Hello from the writer program!
3. Message Queues:
Message queues allow processes to exchange messages in a queue-like structure.
They are identified by a message queue identifier (MQID).
Program: Using Message Queues
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>
#define MSG_SIZE 100
struct message {
long msg_type;
char msg_text[MSG_SIZE];
};
int main() {
key_t key = ftok("msg_queue", 65); // Generate unique key
int msgid = msgget(key, 0666 | IPC_CREAT); // Create message queue
if (msgid < 0) {
perror("Message queue creation failed");
return 1;
}
if (fork() == 0) { // Child process (Receiver)
struct message msg;
msgrcv(msgid, &msg, sizeof(msg.msg_text), 1, 0);
printf("Child received message: %s\n", msg.msg_text);
} else { // Parent process (Sender)
struct message msg;
msg.msg_type = 1; // Type of the message
strcpy(msg.msg_text, "Hello from the message queue!");
msgsnd(msgid, &msg, sizeof(msg.msg_text), 0);
printf("Parent sent message: %s\n", msg.msg_text);
24
}
// Cleanup message queue
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
Sample Output:
Parent sent message: Hello from the message queue!
Child received message: Hello from the message queue!
4.Shared Memory
Shared memory allows multiple processes to access a common memory segment
for communication.
Program: Using Shared Memory
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>
#define SHM_SIZE 1024
int main() {
key_t key = ftok("shm_file", 65); // Generate unique key
int shmid = shmget(key, SHM_SIZE, 0666 | IPC_CREAT); // Create shared memory
if (shmid < 0) {
perror("Shared memory creation failed");
return 1;
}
char *shm_ptr = (char *) shmat(shmid, NULL, 0); // Attach shared memory
if (fork() == 0) { // Child process
sleep(2); // Ensure parent writes first
printf("Child received message: %s\n", shm_ptr);
} else { // Parent process
strcpy(shm_ptr, "Hello from the shared memory!");
printf("Parent wrote message: %s\n", shm_ptr);
}
// Detach and clean up shared memory
shmdt(shm_ptr);
shmctl(shmid, IPC_RMID, NULL);
return 0;
25
}
Sample Output:
Parent Output:
Parent wrote message: Hello from the shared memory!
Child Output:
Child received message: Hello from the shared memory!
26
6.write c program to simulate the following memory management techniques
a) paging b) segmentation with simple algorithm.
Paging is a memory management scheme that eliminates the need for contiguous
allocation of physical memory. It divides both physical memory and logical memory
into fixed-size blocks called pages and frames.
27
printf("Page %d is already loaded in frame %d.\n", page_number,
page_table[page_number]);
} else {
int free_frame = find_free_frame();
if (free_frame != -1) {
page_table[page_number] = free_frame;
memory[free_frame] = page_number;
printf("Page %d loaded into frame %d.\n", page_number, free_frame);
} else {
printf("Memory is full! Cannot load page %d.\n", page_number);
}
}
}
int main() {
initialize_page_table();
initialize_memory();
access_page(0); // Accessing page 0
access_page(1); // Accessing page 1
access_page(3); // Accessing page 3
access_page(0); // Accessing page 0 again (already loaded)
access_page(5); // Accessing page 5
access_page(6); // Accessing page 6 (memory is full now)
return 0;
}
Sample Output:
Page 0 loaded into frame 0.
Page 1 loaded into frame 1.
Page 3 loaded into frame 2.
Page 0 is already loaded in frame 0.
Page 5 loaded into frame 3.
Memory is full! Cannot load page 6.
28
2. Segmentation
Segmentation is a memory management technique that divides the program's
memory into segments based on logical divisions such as functions, arrays, etc.
29
printf("Invalid segment number!\n");
return;
}
if (segment_table[segment_number].base == -1) {
printf("Segment %d is not allocated yet.\n", segment_number);
return;
}
if (offset < 0 || offset >= segment_table[segment_number].limit) {
printf("Invalid memory access: Offset out of bounds for segment %d.\n",
segment_number);
} else {
printf("Accessing memory at Segment %d, Offset %d (Base = %d, Limit =
%d)\n",
segment_number, offset,
segment_table[segment_number].base,
segment_table[segment_number].limit);
}
}
int main() {
initialize_segment_table();
allocate_segment(0, 1000, 500); // Allocate segment 0 with base 1000 and
limit 500
allocate_segment(1, 2000, 300); // Allocate segment 1 with base 2000 and
limit 300
access_memory(0, 400); // Access memory within segment 0
access_memory(1, 350); // Access memory within segment 1
access_memory(0, 600); // Invalid access (out of bounds)
access_memory(2, 100); // Access unallocated segment 2
return 0;
}
Sample Output:
Segment 0 allocated: Base = 1000, Limit = 500
Segment 1 allocated: Base = 2000, Limit = 300
Accessing memory at Segment 0, Offset 400 (Base = 1000, Limit = 500)
Accessing memory at Segment 1, Offset 350 (Base = 2000, Limit = 300)
Invalid memory access: Offset out of bounds for segment 0.
Segment 2 is not allocated yet.
30
7.write c program to simulate pagr replacement policies a) Fcfs b) LRU c) optimal.
1. FCFS (First-Come, First-Served) Page Replacement
Algorithm Steps:
1. When a page is referenced, check if it is already in memory.
2. If the page is not in memory, replace the first page that was loaded (i.e., the
page that arrived first).
3. Keep track of the pages that are in memory and replace them when
necessary.
#include <stdio.h>
#include <stdlib.h>
#define FRAME_SIZE 3
#define PAGE_COUNT 8
void fcfs_page_replacement(int pages[], int n) {
int frames[FRAME_SIZE];
int i, j, page, page_faults = 0;
// Initialize frames to -1 (empty)
for (i = 0; i < FRAME_SIZE; i++) {
frames[i] = -1;
}
for (i = 0; i < n; i++) {
page = pages[i];
int page_found = 0;
// Check if the page is already in memory
for (j = 0; j < FRAME_SIZE; j++) {
if (frames[j] == page) {
page_found = 1;
break;
}
}
// If the page is not in memory, replace the first one
if (!page_found) {
frames[i % FRAME_SIZE] = page;
page_faults++;
31
printf("Page %d loaded: ", page);
for (j = 0; j < FRAME_SIZE; j++) {
printf("%d ", frames[j]);
}
printf("\n");
}
}
printf("Total Page Faults: %d\n", page_faults);
}
int main() {
int pages[PAGE_COUNT] = {7, 0, 1, 2, 0, 3, 0, 4};
fcfs_page_replacement(pages, PAGE_COUNT);
return 0;
}
Sample Output for FCFS:
Page 7 loaded: 7 -1 -1
Page 0 loaded: 7 0 -1
Page 1 loaded: 7 0 1
Page 2 loaded: 2 0 1
Page 0 loaded: 2 0 1
Page 3 loaded: 2 3 1
Page 0 loaded: 0 3 1
Page 4 loaded: 0 3 4
Total Page Faults: 6
32
2. LRU (Least Recently Used) Page Replacement
Algorithm Steps:
1. When a page is referenced, check if it is already in memory.
2. If the page is in memory, mark it as recently used.
3. If the page is not in memory, replace the least recently used page.
#include <stdio.h>
#include <stdlib.h>
#define FRAME_SIZE 3
#define PAGE_COUNT 8
void lru_page_replacement(int pages[], int n) {
int frames[FRAME_SIZE], last_used[FRAME_SIZE];
int i, j, page, page_faults = 0, time = 0;
// Initialize frames to -1 (empty)
for (i = 0; i < FRAME_SIZE; i++) {
frames[i] = -1;
last_used[i] = -1;
}
for (i = 0; i < n; i++) {
page = pages[i];
int page_found = 0;
// Check if the page is already in memory
for (j = 0; j < FRAME_SIZE; j++) {
if (frames[j] == page) {
page_found = 1;
last_used[j] = time++;
break;
}
}
// If the page is not in memory, replace the least recently used page
if (!page_found) {
int lru = 0;
for (j = 1; j < FRAME_SIZE; j++) {
if (last_used[j] < last_used[lru]) {
lru = j;
}
33
}
frames[lru] = page;
last_used[lru] = time++;
page_faults++;
printf("Page %d loaded: ", page);
for (j = 0; j < FRAME_SIZE; j++) {
printf("%d ", frames[j]);
}
printf("\n");
}
}
printf("Total Page Faults: %d\n", page_faults);
}
int main() {
int pages[PAGE_COUNT] = {7, 0, 1, 2, 0, 3, 0, 4};
lru_page_replacement(pages, PAGE_COUNT);
return 0;
}
34
3. Optimal Page Replacement
Algorithm Steps:
1. When a page is referenced, check if it is already in memory.
2. If the page is not in memory, replace the page that will not be used for the
longest time in the future.
3. This replacement strategy minimizes page faults but requires knowledge of
future references.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#define FRAME_SIZE 3
#define PAGE_COUNT 8
int find_optimal(int frames[], int future[], int n) {
int farthest = -1, index = -1;
for (int i = 0; i < FRAME_SIZE; i++) {
int j;
for (j = n; j < PAGE_COUNT; j++) {
if (frames[i] == future[j]) {
if (j > farthest) {
farthest = j;
index = i;
}
break;
}
}
if (j == PAGE_COUNT) {
return i;
}
}
return index;
}
void optimal_page_replacement(int pages[], int n) {
35
int frames[FRAME_SIZE], future[PAGE_COUNT];
int page_faults = 0, i, j;
// Initialize frames to -1 (empty)
for (i = 0; i < FRAME_SIZE; i++) {
frames[i] = -1;
}
for (i = 0; i < n; i++) {
future[i] = pages[i];
}
for (i = 0; i < n; i++) {
int page = pages[i];
int page_found = 0;
// Check if the page is already in memory
for (j = 0; j < FRAME_SIZE; j++) {
if (frames[j] == page) {
page_found = 1;
break;
}
}
// If the page is not in memory, replace the optimal page
if (!page_found) {
int replace_index = find_optimal(frames, future, i + 1);
frames[replace_index] = page;
page_faults++;
printf("Page %d loaded: ", page);
for (j = 0; j < FRAME_SIZE; j++) {
printf("%d ", frames[j]);
}
printf("\n");
}
}
printf("Total Page Faults: %d\n", page_faults);
}
int main() {
int pages[PAGE_COUNT] = {7, 0, 1, 2, 0, 3, 0, 4};
optimal_page_replacement(pages, PAGE_COUNT);
return 0;
}
37