Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Least Recently Used (LRU) Page Replacement Algorithm
- #include <stdio.h>
- #include <stdbool.h>
- // Function which runs the algorithm and in the end, returns no. of page faults
- int LRU_algorithm(int totalPages, int pages[], int totalFrames, int frames[])
- {
- int i, j;
- int pageFaults = 0;
- for (i = 0; i < totalPages; i++)
- {
- int currentPage = pages[i];
- // Check if Page Already Exists
- bool found = false;
- int k;
- for (k = 0; k < totalFrames; k++)
- {
- if (frames[k] == currentPage)
- {
- found = true;
- break;
- }
- }
- // If Page Already Exists, Page Hit
- if (found == true)
- {
- int temp = frames[k];
- for(; k < totalFrames - 1; k++) // (This has to do something with current page, dk what's happening)
- {
- frames[k] = frames[k + 1];
- }
- frames[totalFrames - 1] = temp;
- for (j = 0; j < totalFrames; j++)
- {
- printf("%d \t", frames[j]);
- }
- printf("Page Hit !\n");
- }
- // If Not
- else
- {
- if(i < totalFrames)
- {
- frames[i] = currentPage;
- }
- else
- {
- for(k = 0; k < totalFrames - 1; k++)
- {
- frames[k] = frames[k + 1];
- }
- frames[totalFrames - 1] = currentPage;
- }
- // Increment Page Faults
- pageFaults++;
- for (j = 0; j < totalFrames; j++)
- {
- printf("%d \t", frames[j]);
- }
- printf("Page Fault !\n");
- }
- }
- return pageFaults;
- }
- int main()
- {
- int totalPages = 13;
- int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
- int totalFrames = 4;
- int frames[totalFrames];
- int i;
- for (i = 0; i < totalFrames; i++)
- {
- frames[i] = -1;
- }
- printf("Total Number of Page Faults = %d\n", LRU_algorithm(totalPages, pages, totalFrames, frames));
- }
Advertisement
Add Comment
Please, Sign In to add comment