Sreekar_0125

LRU 2

Aug 14th, 2023
1,115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.17 KB | None | 0 0
  1. // Least Recently Used (LRU) Page Replacement Algorithm
  2. #include <stdio.h>
  3. #include <stdbool.h>
  4.  
  5. // Function which runs the algorithm and in the end, returns no. of page faults
  6.  
  7. int LRU_algorithm(int totalPages, int pages[], int totalFrames, int frames[])
  8. {
  9.     int i, j;
  10.     int pageFaults = 0;
  11.  
  12.     for (i = 0; i < totalPages; i++)
  13.     {
  14.         int currentPage = pages[i];
  15.  
  16.         // Check if Page Already Exists
  17.         bool found = false;
  18.         int k;
  19.         for (k = 0; k < totalFrames; k++)
  20.         {
  21.             if (frames[k] == currentPage)
  22.             {
  23.                 found = true;
  24.                 break;
  25.             }
  26.         }
  27.         // If Page Already Exists, Page Hit
  28.         if (found == true)
  29.         {
  30.             int temp = frames[k];
  31.             for(; k < totalFrames - 1; k++) // (This has to do something with current page, dk what's happening)
  32.             {
  33.                 frames[k] = frames[k + 1];
  34.             }
  35.             frames[totalFrames - 1] = temp;
  36.             for (j = 0; j < totalFrames; j++)
  37.             {
  38.                 printf("%d \t", frames[j]);
  39.             }
  40.             printf("Page Hit !\n");
  41.         }
  42.         // If Not
  43.         else
  44.         {
  45.             if(i < totalFrames)
  46.             {
  47.                 frames[i] = currentPage;
  48.             }
  49.             else
  50.             {
  51.                 for(k = 0; k < totalFrames - 1; k++)
  52.                 {
  53.                     frames[k] = frames[k + 1];
  54.                 }
  55.                 frames[totalFrames - 1] = currentPage;      
  56.             }
  57.             // Increment Page Faults
  58.             pageFaults++;
  59.             for (j = 0; j < totalFrames; j++)
  60.             {
  61.                 printf("%d \t", frames[j]);
  62.             }
  63.             printf("Page Fault !\n");
  64.         }
  65.     }
  66.     return pageFaults;
  67. }
  68.  
  69. int main()
  70. {
  71.     int totalPages = 13;
  72.     int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
  73.  
  74.     int totalFrames = 4;
  75.     int frames[totalFrames];
  76.  
  77.     int i;
  78.     for (i = 0; i < totalFrames; i++)
  79.     {
  80.         frames[i] = -1;
  81.     }
  82.  
  83.     printf("Total Number of Page Faults = %d\n", LRU_algorithm(totalPages, pages, totalFrames, frames));
  84. }
Advertisement
Add Comment
Please, Sign In to add comment