Write the simulation program to implement demand paging and show the page scheduling and total number of page faults for the following given page reference string. Give input n as the number of memory frames. Reference String: 2,5,2,8,5,4,1,2,3,2,6,1,2,5,9,8 Implement MRU
#include <stdio.h>
#include <stdlib.h>
// Function to find the index of the page that is most recently used
int findMRUPage(int frames[], int recent[], int numFrames) {
int maxIndex = 0;
int maxRecent = recent[frames[0]];
for (int i = 1; i < numFrames; i++) {
if (recent[frames[i]] > maxRecent) {
maxRecent = recent[frames[i]];
maxIndex = i;
}
}
return maxIndex;
}
// Function to simulate demand paging with MRU page replacement
void demandPagingMRU(int referenceString[], int n, int numFrames) {
int frames[numFrames];
int pageFaults = 0;
int recent[numFrames]; // Index indicating how recently each page was used
for (int i = 0; i < numFrames; i++) {
frames[i] = -1; // Initialize frames to empty
recent[i] = -1; // Initialize recent index to -1 (never used)
}
printf("Page Schedule:\n");
for (int i = 0; i < n; i++) {
int page = referenceString[i];
int found = 0;
for (int j = 0; j < numFrames; j++) {
if (frames[j] == page) {
recent[j] = i; // Update the recent index
found = 1;
break;
}
}
if (!found) {
int mruIndex = findMRUPage(frames, recent, numFrames);
frames[mruIndex] = page;
recent[mruIndex] = i;
pageFaults++;
printf("Page %d -> ", page);
for (int j = 0; j < numFrames; j++) {
if (frames[j] == -1) {
printf("M ");
} else {
printf("%d ", frames[j]);
}
}
printf(" (Page Fault)\n");
} else {
printf("Page %d -> ", page);
for (int j = 0; j < numFrames; j++) {
if (frames[j] == -1) {
printf("M ");
} else {
printf("%d ", frames[j]);
}
}
printf("\n");
}
}
printf("\nTotal Page Faults: %d\n", pageFaults);
}
int main() {
int numFrames;
int n;
printf("Enter the number of memory frames: ");
scanf("%d", &numFrames);
printf("Enter the number of pages in the reference string: ");
scanf("%d", &n);
int referenceString[n];
printf("Enter the reference string (separated by spaces): ");
for (int i = 0; i < n; i++) {
scanf("%d", &referenceString[i]);
}
demandPagingMRU(referenceString, n, numFrames);
return 0;
}

Comments
Post a Comment