Write the simulation program for demand paging and show the page scheduling and total number of page faults according the LRU page replacement algorithm. Assume the memory of n frames.
Reference String : 2, 4, 5, 6, 9, 4, 7, 3, 4, 5, 6, 7, 2, 4, 7, 1
Reference String : 2, 4, 5, 6, 9, 4, 7, 3, 4, 5, 6, 7, 2, 4, 7, 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FRAMES 100
#define REFERENCE_STRING_LENGTH 16
// Function prototypes
void print_memory(int memory[], int num_frames);
int main() {
int memory[MAX_FRAMES];
int reference_string[REFERENCE_STRING_LENGTH] = {2, 4, 5, 6, 9, 4, 7, 3, 4, 5, 6, 7, 2, 4, 7, 1};
int num_frames; // Number of frames in memory
int num_references = REFERENCE_STRING_LENGTH; // Length of the reference string
int page_faults = 0;
int frame_count = 0; // Current number of pages in memory
int lru_order[MAX_FRAMES]; // To track the order of page usage
int lru_index = 0; // To track the position in lru_order
// Initialize the memory with -1 (indicating empty frames)
printf("Enter the number of frames: ");
scanf("%d", &num_frames);
if (num_frames > MAX_FRAMES) {
printf("Number of frames exceeds maximum limit.\n");
return 1;
}
// Initialize memory and lru_order
for (int i = 0; i < num_frames; i++) {
memory[i] = -1;
}
// Process each page in the reference string
for (int i = 0; i < num_references; i++) {
int current_page = reference_string[i];
int page_found = 0;
// Check if the page is already in memory
for (int j = 0; j < num_frames; j++) {
if (memory[j] == current_page) {
page_found = 1;
// Update LRU order
lru_order[lru_index++] = current_page;
if (lru_index >= num_frames) lru_index = 0; // Circular increment
break;
}
}
if (!page_found) {
// Page fault
page_faults++;
printf("Page fault! Reference: %d\n", current_page);
if (frame_count < num_frames) {
// Add new page to memory
memory[frame_count++] = current_page;
lru_order[lru_index++] = current_page;
if (lru_index >= num_frames) lru_index = 0; // Circular increment
} else {
// Find the least recently used page
int lru_page = lru_order[lru_index];
for (int j = 0; j < num_frames; j++) {
if (memory[j] == lru_page) {
memory[j] = current_page;
lru_index = (lru_index + 1) % num_frames; // Move LRU index
lru_order[lru_index] = current_page; // Update LRU order
break;
}
}
}
} else {
printf("Page hit! Reference: %d\n", current_page);
}
// Print the state of memory
print_memory(memory, num_frames);
}
printf("Total number of page faults: %d\n", page_faults);
return 0;
}
// Function to print the state of the memory
void print_memory(int memory[], int num_frames) {
printf("Memory state: ");
for (int i = 0; i < num_frames; i++) {
if (memory[i] != -1) {
printf("%d ", memory[i]);
} else {
printf("_ ");
}
}
printf("\n");
}
0 Comments