-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpagereplacment.cpp
150 lines (138 loc) · 3.47 KB
/
pagereplacment.cpp
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include <stdio.h>
int lru(int frames[], int pages[], int n_frames, int n_pages)
{
int cache[n_frames];
int page_faults = 0;
int i, j, k, min;
for (i = 0; i < n_pages; i++)
{
int found = 0;
for (j = 0; j < n_frames; j++)
{
if (cache[j] == pages[i])
{
found = 1;
break;
}
}
if (!found)
{
min = 0;
for (j = 1; j < n_frames; j++)
{
if (frames[j] < frames[min])
{
min = j;
}
}
cache[min] = pages[i];
frames[min] = i;
page_faults++;
}
}
return page_faults;
}
int fifo(int frames[], int pages[], int n_frames, int n_pages)
{
int cache[n_frames];
int page_faults = 0;
int i, j, k, oldest;
for (i = 0; i < n_pages; i++)
{
int found = 0;
for (j = 0; j < n_frames; j++)
{
if (cache[j] == pages[i])
{
found = 1;
break;
}
}
if (!found)
{
oldest = 0;
for (j = 1; j < n_frames; j++)
{
if (frames[j] < frames[oldest])
{
oldest = j;
}
}
cache[oldest] = pages[i];
frames[oldest] = i;
page_faults++;
}
}
return page_faults;
}
int optimal(int frames[], int pages[], int n_frames, int n_pages)
{
int cache[n_frames];
int page_faults = 0;
int i, j, k, max, index;
for (i = 0; i < n_pages; i++)
{
int found = 0;
for (j = 0; j < n_frames; j++)
{
if (cache[j] == pages[i])
{
found = 1;
break;
}
}
if (!found)
{
max = 0;
for (j = 0; j < n_frames; j++)
{
int found2 = 0;
for (k = i + 1; k < n_pages; k++)
{
if (cache[j] == pages[k])
{
found2 = 1;
break;
}
}
if (!found2)
{
max = j;
break;
}
if (frames[j] > frames[max])
{
max = j;
}
}
cache[max] = pages[i];
frames[max] = i;
page_faults++;
}
}
return page_faults;
}
int main()
{
int n_frames, n_pages;
printf("Enter the number of frames: ");
scanf("%d", &n_frames);
printf("Enter the number of pages: ");
scanf("%d", &n_pages);
int frames[n_frames], pages[n_pages];
printf("Enter the pages: ");
for (int i = 0; i < n_pages; i++)
{
scanf("%d", &pages[i]);
}
// LRU
int page_faults = lru(frames, pages, n_frames, n_pages);
printf("LRU: %d page faults\n", page_faults);
// FIFO
page_faults = fifo(frames, pages, n_frames, n_pages);
printf("FIFO: %d page faults\n", page_faults);
// Optimal
page_faults = optimal(frames, pages, n_frames, n_pages);
printf("Optimal: %d page faults\n", page_faults);
return 0;
}