Write the simulation program for demand paging and show the page scheduling and total number of page faults according the MRU page replacement algorithm. Assume the memory of n frames.
Reference String : 7, 5, 4, 8, 5, 7, 2, 3, 1, 3, 5, 9, 4, 6, 2
Reference String : 7, 5, 4, 8, 5, 7, 2, 3, 1, 3, 5, 9, 4, 6, 2
#include <stdio.h>
#include <stdlib.h>
#define MAX_FRAMES 100
#define REFERENCE_STRING_LENGTH 15
// Function prototypes
void print_memory(int memory[], int num_frames);
int main() {
int memory[MAX_FRAMES];
int reference_string[REFERENCE_STRING_LENGTH] = {7, 5, 4, 8, 5, 7, 2, 3, 1, 3, 5, 9, 4, 6, 2};
int num_frames; // Number of frames in memory
int num_references = REFERENCE_STRING_LENGTH; // Length of the reference string
int page_faults = 0;
// 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
for (int i = 0; i < num_frames; i++) {
memory[i] = -1;
}
printf("Reference String: ");
for (int i = 0; i < num_references; i++) {
printf("%d ", reference_string[i]);
}
printf("\n");
// 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;
int recent_index = -1;
// Check if the page is already in memory
for (int j = 0; j < num_frames; j++) {
if (memory[j] == current_page) {
page_found = 1;
recent_index = j;
break;
}
}
if (!page_found) {
// Page fault
page_faults++;
printf("Page fault! Reference: %d\n", current_page);
// Find the most recently used page (the page that will be replaced)
if (memory[0] != -1) {
// Replace the most recently used page
for (int j = 0; j < num_frames; j++) {
if (memory[j] == memory[recent_index]) {
recent_index = j;
break;
}
}
}
// Replace the page in memory
if (recent_index != -1) {
memory[recent_index] = current_page;
} else {
// Find an empty slot
for (int j = 0; j < num_frames; j++) {
if (memory[j] == -1) {
recent_index = j;
break;
}
}
if (recent_index != -1) {
memory[recent_index] = current_page;
}
}
} 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