0% found this document useful (0 votes)
7 views2 pages

LRUpage Replacement

The document contains a C program that implements the Least Recently Used (LRU) page replacement algorithm. It initializes frames and tracks page usage, replacing the least recently used page when a page fault occurs. The program outputs the current state of the frames after each page reference and the total number of page faults at the end.

Uploaded by

naimama1971
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

LRUpage Replacement

The document contains a C program that implements the Least Recently Used (LRU) page replacement algorithm. It initializes frames and tracks page usage, replacing the least recently used page when a page fault occurs. The program outputs the current state of the frames after each page reference and the total number of page faults at the end.

Uploaded by

naimama1971
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

#include <stdio.

h>

#define MAX_PAGES 10

void lru(int pages[], int n, int frames) {


int frame[frames];
int pageFaults = 0;
int lastUsed[frames];

for (int i = 0; i < frames; i++) {


frame[i] = -1; // Initialize frames with -1 (empty)
lastUsed[i] = -1; // Initialize lastUsed time
}

for (int i = 0; i < n; i++) {


int page = pages[i];
int found = 0;

// Check if the page is already in a frame


for (int j = 0; j < frames; j++) {
if (frame[j] == page) {
found = 1;
lastUsed[j] = i; // Update the last used time
break;
}
}

if (!found) {
int lruIndex = 0;
for (int j = 1; j < frames; j++) {
if (lastUsed[j] < lastUsed[lruIndex]) {
lruIndex = j;
}
}
frame[lruIndex] = page; // Replace the LRU page
lastUsed[lruIndex] = i;
pageFaults++;
}

printf("Page %d: ", page);


for (int j = 0; j < frames; j++) {
if (frame[j] != -1) {
printf("%d ", frame[j]);
}
}
printf("\n");
}

printf("\nTotal Page Faults: %d\n", pageFaults);


}

int main() {
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3};
int n = sizeof(pages) / sizeof(pages[0]);
int frames = 3;

lru(pages, n, frames);

return 0;
}

You might also like