模拟内存的页式管理,实现内存的分配和调用,完成虚拟内存地址序列和物理内存的对应。在内存调用出现缺页时,调入程序的内存页。在出现无空闲页面时,使用先进先出(FIFO)算法实现页面置换。
#include <stdio.h>
#include <stdlib.h>
#define TOTAL_PAGES 320
#define TOTAL_INSTRUCTIONS 1000
#define INVALID -1
// Describes the page structure
typedef struct {
int page_num;
int pframe_num;
int timestamp;
int counter;
} page_type;
// Describes the physical frame structure
typedef struct pf_struct {
int pframe_num;
struct pf_struct *next;
} pf_type;
// Global variables
int diseffect;
page_type pl[TOTAL_PAGES];
pf_type pfc[TOTAL_PAGES];
pf_type *freepf_head;
pf_type *busypf_head, *busypf_tail;
// Function prototypes
void initialize(int total_pf);
void FIFO(int total_pf);
int main() {
// You need to define total_vp and total_instruction somewhere in your code.
int total_vp = 10; // Replace with your actual value
int total_instruction = 20; // Replace with your actual value
printf("模拟内存地址序列:\n");
for (int i = 0; i < total_instruction; i++) {
printf("%d ", i);
}
printf("\n");
FIFO(total_vp);
return 0;
}
void initialize(int total_pf) {
int i;
diseffect = 0;
for (i = 0; i < TOTAL_PAGES; i++) {
pl[i].page_num = i;
pl[i].pframe_num = INVALID;
pl[i].counter = 0;
pl[i].timestamp = -1;
}
for (i = 0; i < total_pf - 1; i++) {
pfc[i].next = &pfc[i + 1];
pfc[i].pframe_num = i;
}
pfc[total_pf - 1].next = NULL;
pfc[total_pf - 1].pframe_num = total_pf - 1;
freepf_head = &pfc[0];
}
void FIFO(int total_pf) {
int i;
pf_type *p;
initialize(total_pf);
busypf_head = busypf_tail = NULL;
printf("模拟内存访问和页面置换:\n");
for (i = 0; i < TOTAL_INSTRUCTIONS; i++) {
printf("访问地址:%d\n", i);
if (pl[i].pframe_num == INVALID) {
diseffect += 1;
if (freepf_head == NULL) {
p = busypf_head->next;
pl[busypf_head->pframe_num].pframe_num = INVALID;
freepf_head = busypf_head;
freepf_head->next = NULL;
busypf_head = p;
printf("发生缺页,页面置换:替换页 %d -> 新页 %d\n", freepf_head->pframe_num, i);
}
p = freepf_head->next;
freepf_head->next = NULL;
freepf_head->pframe_num = i;
pl[i].pframe_num = freepf_head->pframe_num;
if (busypf_tail == NULL)
busypf_head = busypf_tail = freepf_head;
else {
busypf_tail->next = freepf_head;
busypf_tail = freepf_head;
}
freepf_head = p;
}
}
printf("FIFO: %6.4f\n", 1 - (float)diseffect / TOTAL_INSTRUCTIONS);
}