Skip to content

Commit a8c39d3

Browse files
Create FIFO-paging-algorithm.c
1 parent b46edef commit a8c39d3

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

FIFO-paging-algorithm.c

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
Simulating the physical memory and its paging process
3+
using the FIFO algorithm and
4+
counting the page faults
5+
*/
6+
7+
#include <stdio.h>
8+
#include <stdlib.h>
9+
#include <string.h>
10+
11+
12+
int main(int argc, char** argv) {
13+
14+
if (argc != 4) {
15+
printf("Wrong inputs. should be 3 arguments!");
16+
return 0;
17+
}
18+
19+
unsigned int noPhysPages = atoi(argv[1]);
20+
unsigned int pageSize = atoi(argv[2]);
21+
char* fileName = argv[3];
22+
unsigned int front = 0, rear = 0, count = 0;
23+
unsigned int pageFaults = 0;
24+
unsigned int address, page;
25+
unsigned int references = 0;
26+
27+
if (noPhysPages == 0 || pageSize == 0) {
28+
printf("page size or no physical pages cant be 0!");
29+
return 0;
30+
}
31+
32+
printf("No physical pages = %u, page size = %u\n", noPhysPages, pageSize);
33+
printf("Reading memory trace from %s... \n", fileName);
34+
35+
FILE* fp = fopen(fileName, "r");
36+
37+
unsigned int* queue = malloc(noPhysPages * sizeof(unsigned int));
38+
39+
while (fscanf(fp, "%u", &address) != EOF) {
40+
page = address / pageSize;
41+
int found = 0;
42+
43+
for (unsigned int i = 0; i < count; i++) {
44+
unsigned int idx = (front + i) % noPhysPages;
45+
if (queue[idx] == page) {
46+
found = 1;
47+
break;
48+
}
49+
}
50+
51+
if (!found) {
52+
pageFaults++;
53+
if (count < noPhysPages) {
54+
// Queue not full, add page at rear
55+
queue[rear] = page;
56+
rear = (rear + 1) % noPhysPages;
57+
count++;
58+
} else {
59+
// Queue full, replace the oldest page at front
60+
queue[front] = page;
61+
front = (front + 1) % noPhysPages;
62+
rear = (rear + 1) % noPhysPages;
63+
}
64+
}
65+
references++;
66+
}
67+
fclose(fp);
68+
69+
printf("Read %u memory references\n", references);
70+
printf("Result: %u page faults\n", pageFaults);
71+
72+
free(queue);
73+
return EXIT_SUCCESS;
74+
}
75+

0 commit comments

Comments
 (0)