一、实验代码
#include <stdio.h>
#include <stdlib.h>
typedef struct item
{
int num;
int time;
} Pro;
int pageNum;
int memoryNum;
void print ( Pro * page1) ;
int Search ( int num1, Pro * memory1) ;
int main ( void )
{
int i;
int curmemory;
int missNum;
float missRate;
char c;
Pro * page;
Pro * memory;
printf ( "输入系统分配给作业的主存中的页面数:" ) ;
scanf ( "%d" , & pageNum) ;
printf ( "输入内存页面数:" ) ;
scanf ( "%d" , & memoryNum) ;
page= ( Pro* ) malloc ( sizeof ( Pro) * pageNum) ;
memory= ( Pro* ) malloc ( sizeof ( Pro) * memoryNum) ;
for ( i= 0 ; i< pageNum; i++ )
{
printf ( "第%d个页面号为:" , i) ;
scanf ( "%d" , & page[ i] . num) ;
page[ i] . time= 0 ;
}
do {
for ( i= 0 ; i< memoryNum; i++ )
{
memory[ i] . num= - 1 ;
memory[ i] . time= - 1 ;
}
printf ( "*****f:FIFO页面置换****\n" ) ;
printf ( "*****o:OPT页面置换****\n" ) ;
printf ( "*****l:LRU页面置换****\n" ) ;
printf ( "*****请选择操作类型(f,o,l),按其他键结束****\n" ) ;
getchar ( ) ;
scanf ( "%c" , & c) ;
i= 0 ;
curmemory= 0 ;
if ( c== 'f' )
{
missNum= 0 ;
printf ( "FIFO页面置换情况: \n" ) ;
for ( i= 0 ; i< pageNum; i++ )
{
if ( Search ( page[ i] . num, memory) < 0 )
{
missNum++ ;
memory[ curmemory] . num= page[ i] . num;
print ( memory) ;
curmemory= ( curmemory+ 1 ) % memoryNum;
}
}
missRate= ( float ) missNum/ pageNum;
printf ( "缺页次数:%d 缺页率: %f\n" , missNum, missRate) ;
}
if ( c== 'o' )
{
missNum= 0 ;
curmemory= 0 ;
printf ( "Optimal页面置换情况 :\n" ) ;
for ( i= 0 ; i< pageNum; i++ )
{
if ( Search ( page[ i] . num, memory) < 0 )
{
int tem;
int opt= 0 ;
for ( int k= 0 ; k< memoryNum; k++ )
{
if ( memory[ k] . num== - 1 )
{
curmemory= k;
break ;
}
tem= 0 ;
int j;
for ( j= i+ 1 ; j< pageNum; j++ )
{
if ( page[ j] . num== memory[ k] . num)
{
if ( tem> opt)
{
opt= tem;
curmemory= k;
}
break ;
}
else tem++ ;
}
if ( j== pageNum)
{
opt= tem;
curmemory= k;
}
}
missNum++ ;
memory[ curmemory] . num= page[ i] . num;
print ( memory) ;
}
}
missRate= ( float ) missNum/ pageNum;
printf ( "缺页次数: %d 缺页率: %f\n" , missNum, missRate) ;
}
if ( c== 'l' )
{
missNum= 0 ;
curmemory= 0 ;
printf ( "LRU页面置换情况: \n" ) ;
for ( i= 0 ; i< pageNum; i++ )
{
int rec= Search ( page[ i] . num, memory) ;
if ( rec< 0 )
{
missNum++ ;
for ( int j= 0 ; j< memoryNum; j++ )
if ( memory[ j] . time== - 1 )
{
curmemory= j;
break ;
}
else if ( memory[ j] . time> memory[ curmemory] . time)
curmemory= j;
memory[ curmemory] . num= page[ i] . num;
memory[ curmemory] . time= 0 ;
print ( memory) ;
}
else memory[ rec] . time= 0 ;
for ( int j= 0 ; j< memoryNum; j++ )
if ( memory[ j] . num!= - 1 )
memory[ j] . time++ ;
}
missRate= ( float ) missNum/ pageNum;
printf ( " 缺页次数: %d 缺页率: %f\n" , missNum, missRate) ;
}
} while ( c== 'f' || c== 'l' || c== 'o' ) ;
return 0 ;
}
void print ( Pro * memory1)
{
int j;
for ( j= 0 ; j< memoryNum; j++ )
printf ( "%d " , memory1[ j] . num) ;
printf ( "\n" ) ;
}
int Search ( int num1, Pro * memory1)
{
int j;
for ( j= 0 ; j< memoryNum; j++ )
{
if ( num1== memory1[ j] . num)
return j;
}
return - 1 ;
}
二、实验结果截图
输入各项参数结果图 FIFO页面置换结果 OPT页面置换结果 LRU页面置换结果