-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8_LRU_Page_Replacement.c
More file actions
88 lines (74 loc) · 2.2 KB
/
8_LRU_Page_Replacement.c
File metadata and controls
88 lines (74 loc) · 2.2 KB
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
/*
Page Reference String : 1 2 3 4 1 2 5 1 2 3 4 5
Page Fault Frames: 1 -1 -1
Page Fault Frames: 1 2 -1
Page Fault Frames: 1 2 3
Page Fault Frames: 4 2 3
Page Fault Frames: 4 1 3
Page Fault Frames: 4 1 2
Page Fault Frames: 5 1 2
Page Hit Frames: 5 1 2
Page Hit Frames: 5 1 2
Page Fault Frames: 3 1 2
Page Fault Frames: 3 4 2
Page Fault Frames: 3 4 5
Total Page Faults: 10
*/
#include <stdio.h>
#include <stdbool.h>
void lru(int pages[], int n, int capacity) {
int frames[capacity];
int pageLastUsed[capacity];
int pageFaults = 0;
for (int i = 0; i < capacity; i++) {
frames[i] = -1;
pageLastUsed[i] = -1;
}
for (int i = 0; i < n; i++) {
int currentPage = pages[i];
bool pageFound = false;
for (int j = 0; j < capacity; j++) {
if (frames[j] == currentPage) {
pageFound = true;
pageLastUsed[j] = i;
break;
}
}
if (!pageFound) {
int lruIndex = 0;
int minLastUsed = pageLastUsed[0];
for (int j = 1; j < capacity; j++) {
if (pageLastUsed[j] < minLastUsed) {
minLastUsed = pageLastUsed[j];
lruIndex = j;
}
}
frames[lruIndex] = currentPage;
pageLastUsed[lruIndex] = i;
pageFaults++;
printf("Page Fault \t");
} else {
printf("Page Hit \t");
}
printf("Frames: ");
for (int j = 0; j < capacity; j++)
printf("%d ", frames[j]);
printf("\n");
}
printf("\n\nTotal Page Faults: %d\n", pageFaults);
}
int main() {
int num,frames;
printf("Enter the number of pages : ");
scanf("%d", &num);
int pages[num];
printf("Enter The Reference String : ");
for (int i = 0; i < num; i++) scanf("%d", &pages[i]);
printf("Enter the number of frames : ");
scanf("%d", &frames);
printf("Page Reference String : ");
for (int i = 0; i < num; i++) printf("%d ", pages[i]);
printf("\n\n");
lru(pages, num, frames);
return 0;
}