printf("%d",page[i]);
printf("\n");
getch();
for(ram=1;ram<=32;ram++)
{if(ram==10)getch();
printf("\nblock=%dpages=%d,absentrate:
",ram,j);
printf("FIFO=%0.2f%%",FIFO(ram));
printf("LRU=%0.2f%%",LRU(ram));
printf("OPT=%0.2f%%",OPT(ram));
}
k=k*2;
getch();
}
}
实验小结:
通过本次实验掌握了先进先出和最近最久未使用页面置换算法,同时也对其他的页面置换算法也更加熟悉。
在实验过程中熟悉了C语言的编程环境,并能够用C编程模拟比较也面置换算法,对编程也有一定的提高。
代码:
#include"stdio.h"
#include"stdlib.h"
#include"conio.h"
#include"ctype.h"
//定义页,采用双向链表存储结构
structpage
{
unsignedintnumber;//页号
unsignedintbaseaddress;//页开始地址
//其它信息
structpage*nextpage,*priorpage;//下一页和前一页
};
//定义页表
structpagetable
{
unsignedintpid;//进程号
unsignedintpagenum;//页表大小
unsignedintpagetablesize;//页表最大表目
structpage*head;//页表头指针,指向头结点,头结点指向第一页
};
//FIFO页面访问程序,函数调用时要传递过来页表pt,要访问的页面号accesspage,返回是否发生缺页中断(1是0否)
intaccess(structpagetable*pt,unsignedintaccesspage)
{
structpage*newpage;//新页面
structpage*currentpage=pt->head->nextpage;//当前页
structpage*replacedpage;//要淘汰的页
//在当前页中寻找要访问的页号
while(currentpage&¤tpage->number!
=accesspage)
{
currentpage=currentpage->nextpage;
}
//找到页号则打印√,并返回0
if(currentpage!
=NULL&¤tpage->number==accesspage)
{
printf("√");
return0;
}
//没找到则判断页表是否已经满了,没满则调入新页并打印×返回1
elseif(pt->pagenumpagetablesize)
{
newpage=(structpage*)malloc(sizeof(structpage));
newpage->number=accesspage;
newpage->nextpage=newpage->priorpage=NULL;
newpage->nextpage=pt->head->nextpage;
if(pt->head->nextpage)
{
pt->head->nextpage->priorpage=newpage;
}
pt->head->nextpage=newpage;
newpage->priorpage=pt->head;
pt->pagenum++;
printf("×");
return1;
}
//如页表已经满,则采用fifo算法进行淘汰选择
else
{
currentpage=pt->head->nextpage;
replacedpage=NULL;
while(currentpage->nextpage)
{
currentpage=currentpage->nextpage;
}
replacedpage=currentpage;
if(replacedpage->nextpage)
{
replacedpage->nextpage->priorpage=replacedpage->priorpage;
}
replacedpage->priorpage->nextpage=replacedpage->nextpage;
free(replacedpage);
newpage=(structpage*)malloc(sizeof(structpage));
newpage->number=accesspage;
newpage->nextpage=newpage->priorpage=NULL;
newpage->nextpage=pt->head->nextpage;
if(pt->head->nextpage)
{
pt->head->nextpage->priorpage=newpage;
}
pt->head->nextpage=newpage;
newpage->priorpage=pt->head;
printf("×");
return1;
}
}
main()
{
structpagetablept;
unsignedinttotalabsence=0,totalpagenum=10;
unsignedintrestpage[100];
unsignedinti=0;
pt.pagenum=0;
pt.pagetablesize=3;
pt.head=(structpage*)malloc(sizeof(structpage));
pt.head->nextpage=pt.head->priorpage=NULL;
//从文件获取要读入的页面流
FILE*fp;
fp=fopen("IN.dat","r");
if(fp==NULL)
{printf("cannotopenfileIN.DAT!
");return;}
while(!
feof(fp))
{
fscanf(fp,"%d",&restpage[i]);
i++;
}
fclose(fp);
totalpagenum=i;
printf("thisprogramforfifo\n\n");
//打印要访问的页
for(i=0;i{
printf("%2d",restpage[i]);
}
printf("\n");
//调用函数访问页
for(i=0;i{
totalabsence+=access(&pt,restpage[i]);
}
printf("\nabsencetimes:
%d\ntotalaccesstimes:
%d\nabsenceratio:
%.2f%%\n",totalabsence,totalpagenum,totalabsence*100.0/totalpagenum);
getchar();
}