-
Notifications
You must be signed in to change notification settings - Fork 0
/
enviroment.c
84 lines (73 loc) · 2.26 KB
/
enviroment.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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define PAGE_SIZE 4
#define NUM_VIRTUAL_PAGES 8
#define PHYSICAL_MEMORY_SIZE 4
int physical_memory[PHYSICAL_MEMORY_SIZE][PAGE_SIZE];
int disk_storage[NUM_VIRTUAL_PAGES][PAGE_SIZE];
int page_table[NUM_VIRTUAL_PAGES];
int usage_order[PHYSICAL_MEMORY_SIZE];
int current_usage_index = 0;
void initialize_disk_storage() {
for (int i = 0; i < NUM_VIRTUAL_PAGES; i++) {
for (int j = 0; j < PAGE_SIZE; j++) {
disk_storage[i][j] = i;
}
}
for (int i = 0; i < PHYSICAL_MEMORY_SIZE; i++) {
usage_order[i] = -1;
}
}
bool is_page_in_memory(int virtual_page_number) {
return page_table[virtual_page_number] != -1;
}
void update_usage_order(int physical_slot) {
int i;
for (i = 0; i < PHYSICAL_MEMORY_SIZE; i++) {
if (usage_order[i] == physical_slot) {
break;
}
}
while (i < PHYSICAL_MEMORY_SIZE - 1) {
usage_order[i] = usage_order[i + 1];
i++;
}
usage_order[PHYSICAL_MEMORY_SIZE - 1] = physical_slot;
}
void load_page_from_disk(int virtual_page_number) {
int slot_to_load;
if (current_usage_index < PHYSICAL_MEMORY_SIZE) {
slot_to_load = current_usage_index++;
} else {
int lru_slot = usage_order[0];
page_table[virtual_page_number] = -1;
slot_to_load = lru_slot;
printf("Evicting from slot %d\n", lru_slot);
}
for (int j = 0; j < PAGE_SIZE; j++) {
physical_memory[slot_to_load][j] = disk_storage[virtual_page_number][j];
}
page_table[virtual_page_number] = slot_to_load;
update_usage_order(slot_to_load);
}
void access_page(int virtual_page_number) {
if (is_page_in_memory(virtual_page_number)) {
int physical_slot = page_table[virtual_page_number];
printf("Page %d in memory slot %d\n", virtual_page_number, physical_slot);
update_usage_order(physical_slot);
} else {
printf("Page fault on page %d\n", virtual_page_number);
load_page_from_disk(virtual_page_number);
}
}
int main() {
for (int i = 0; i < NUM_VIRTUAL_PAGES; i++) page_table[i] = -1;
initialize_disk_storage();
access_page(2);
access_page(3);
access_page(2);
access_page(4);
access_page(5);
return 0;
}