|
| 1 | +/* |
| 2 | +Simulating the physical memory and its paging process |
| 3 | +using the Least Recently Used (LRU) algorithm and |
| 4 | +counting the page faults |
| 5 | +*/ |
| 6 | + |
| 7 | +#include <stdio.h> |
| 8 | +#include <stdlib.h> |
| 9 | + |
| 10 | +int findLRU(int* timestamps, int noPhysPages) { |
| 11 | + int min = timestamps[0], lruIndex = 0; |
| 12 | + for (int i = 1; i < noPhysPages; i++) { |
| 13 | + if (timestamps[i] < min) { |
| 14 | + min = timestamps[i]; |
| 15 | + lruIndex = i; |
| 16 | + } |
| 17 | + } |
| 18 | + return lruIndex; |
| 19 | +} |
| 20 | + |
| 21 | +int main(int argc, char** argv) { |
| 22 | + if (argc != 4) { |
| 23 | + printf("Wrong inputs. Should be 3 arguments!\n"); |
| 24 | + return 0; |
| 25 | + } |
| 26 | + |
| 27 | + unsigned int noPhysPages = atoi(argv[1]); |
| 28 | + unsigned int pageSize = atoi(argv[2]); |
| 29 | + char* fileName = argv[3]; |
| 30 | + |
| 31 | + if (noPhysPages == 0 || pageSize == 0) { |
| 32 | + printf("Page size or number of physical pages cannot be 0!\n"); |
| 33 | + return 0; |
| 34 | + } |
| 35 | + |
| 36 | + printf("No physical pages = %u, page size = %u\n", noPhysPages, pageSize); |
| 37 | + printf("Reading memory trace from %s...\n", fileName); |
| 38 | + |
| 39 | + FILE* fp = fopen(fileName, "r"); |
| 40 | + if (fp == NULL) { |
| 41 | + printf("Failed to open file: %s\n", fileName); |
| 42 | + return 0; |
| 43 | + } |
| 44 | + |
| 45 | + unsigned int* frames = malloc(noPhysPages * sizeof(unsigned int)); |
| 46 | + int* timestamps = malloc(noPhysPages * sizeof(int)); |
| 47 | + for (int i = 0; i < noPhysPages; i++) { |
| 48 | + frames[i] = -1; |
| 49 | + timestamps[i] = 0; |
| 50 | + } |
| 51 | + |
| 52 | + unsigned int address, page; |
| 53 | + unsigned int pageFaults = 0, references = 0; |
| 54 | + int time = 0; |
| 55 | + |
| 56 | + while (fscanf(fp, "%u", &address) != EOF) { |
| 57 | + page = address / pageSize; |
| 58 | + int found = 0; |
| 59 | + |
| 60 | + |
| 61 | + for (unsigned int i = 0; i < noPhysPages; i++) { |
| 62 | + if (frames[i] == page) { |
| 63 | + found = 1; // Page found |
| 64 | + timestamps[i] = time++; // Update the access time |
| 65 | + break; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + if (!found) { |
| 70 | + pageFaults++; |
| 71 | + int lruIndex = -1; |
| 72 | + |
| 73 | + if (references < noPhysPages) { |
| 74 | + lruIndex = references; |
| 75 | + } else { |
| 76 | + lruIndex = findLRU(timestamps, noPhysPages); |
| 77 | + } |
| 78 | + |
| 79 | + frames[lruIndex] = page; |
| 80 | + timestamps[lruIndex] = time++; |
| 81 | + } |
| 82 | + references++; |
| 83 | + } |
| 84 | + |
| 85 | + fclose(fp); |
| 86 | + |
| 87 | + printf("Read %u memory references\n", references); |
| 88 | + printf("Result: %u page faults\n", pageFaults); |
| 89 | + |
| 90 | + free(frames); |
| 91 | + free(timestamps); |
| 92 | + return 0; |
| 93 | +} |
0 commit comments