-
Notifications
You must be signed in to change notification settings - Fork 5
/
LRU.c
95 lines (77 loc) · 1.88 KB
/
LRU.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
#define MAX_FRAMES 3
#define MAX_PAGES 20
int frames[MAX_FRAMES];
int counter[MAX_FRAMES];
void initialize() {
for (int i = 0; i < MAX_FRAMES; i++) {
frames[i] = -1;
counter[i] = 0;
}
}
void displayFrames() {
for (int i = 0; i < MAX_FRAMES; i++) {
if (frames[i] != -1)
printf("%d ", frames[i]);
else
printf("- ");
}
printf("\n");
}
int findLRU() {
int max = counter[0];
int lru_frame = 0;
for (int i = 1; i < MAX_FRAMES; i++) {
if (counter[i] > max) {
max = counter[i];
lru_frame = i;
}
}
return lru_frame;
}
void LRU(int pages[], int n) {
int page_faults = 0;
for (int i = 0; i < n; i++) {
int page = pages[i];
int found = 0;
for (int j = 0; j < MAX_FRAMES; j++) {
if (frames[j] == page) {
found = 1;
printf("page %d is already there \n",page);
break;
}
}
if (!found) {
int lru_frame = findLRU();
printf("page %d is loaded in frame %d\n",page,lru_frame);
frames[lru_frame] = page;
counter[lru_frame] = 0;
page_faults++;
}
for (int j = 0; j < MAX_FRAMES; j++) {
counter[j]++;
}
for (int j = 0; j < MAX_FRAMES; j++) {
if (frames[j] == page) {
counter[j] = 0;
break;
}
}
displayFrames();
}
printf("Total Page Faults: %d\n", page_faults);
}
int main() {
int pages[MAX_PAGES];
int n;
printf("Enter number of pages: ");
scanf("%d", &n);
printf("Enter the page reference sequence: ");
for (int i = 0; i < n; i++) {
scanf("%d", &pages[i]);
}
initialize();
LRU(pages, n);
return 0;
}