三种页面置换算法c语言代码
时间: 2024-06-18 10:03:11 浏览: 117
页面置换算法是一种内存管理算法,常用于虚拟内存系统中。常见的三种页面置换算法包括FIFO算法、最优算法(OPT)和最近最久未使用算法(LRU)。以下是三种算法的C语言代码实现。
1. FIFO算法
```
#include <stdio.h>
int main()
{
int pages[100], frames[10], pageNum, frameNum, faults=0, j, k, l, flag;
printf("Enter the number of pages: ");
scanf("%d", &pageNum);
printf("Enter the page reference string: ");
for(j=0; j<pageNum; j++)
scanf("%d", &pages[j]);
printf("Enter the number of frames: ");
scanf("%d", &frameNum);
for(j=0; j<frameNum; j++)
frames[j] = -1;
j = 0;
printf("\nReference String\t Page Frames\n");
for(k=0; k<pageNum; k++)
{
printf("%d\t\t", pages[k]);
flag = 0;
for(l=0; l<frameNum; l++)
{
if(frames[l] == pages[k])
{
flag = 1;
break;
}
}
if(flag == 0)
{
frames[j] = pages[k];
j = (j+1)%frameNum;
faults++;
for(l=0; l<frameNum; l++)
printf("%d\t", frames[l]);
}
printf("\n");
}
printf("\nTotal Page Faults: %d", faults);
return 0;
}
```
2. 最优算法(OPT)
```
#include <stdio.h>
#include <limits.h>
int main()
{
int pages[100], frames[10], pageNum, frameNum, faults=0, j, k, l, m, max, flag;
printf("Enter the number of pages: ");
scanf("%d", &pageNum);
printf("Enter the page reference string: ");
for(j=0; j<pageNum; j++)
scanf("%d", &pages[j]);
printf("Enter the number of frames: ");
scanf("%d", &frameNum);
for(j=0; j<frameNum; j++)
frames[j] = -1;
printf("\nReference String\t Page Frames\n");
for(k=0; k<pageNum; k++)
{
flag = 0;
for(l=0; l<frameNum; l++)
{
if(frames[l] == pages[k])
{
flag = 1;
break;
}
}
if(flag == 0)
{
max = INT_MIN;
for(l=0; l<frameNum; l++)
{
flag = 0;
for(m=k+1; m<pageNum; m++)
{
if(frames[l] == pages[m])
{
flag = 1;
break;
}
}
if(flag == 0 && pages[m] != -1 && max < m)
{
max = m;
j = l;
}
}
frames[j] = pages[k];
faults++;
printf("%d\t\t", pages[k]);
for(l=0; l<frameNum; l++)
printf("%d\t", frames[l]);
printf("\n");
}
}
printf("\nTotal Page Faults: %d", faults);
return 0;
}
```
3. 最近最久未使用算法(LRU)
```
#include <stdio.h>
int main()
{
int pages[100], frames[10], pageNum, frameNum, faults=0, j, k, l, m, min, flag[10], counter=0;
printf("Enter the number of pages: ");
scanf("%d", &pageNum);
printf("Enter the page reference string: ");
for(j=0; j<pageNum; j++)
scanf("%d", &pages[j]);
printf("Enter the number of frames: ");
scanf("%d", &frameNum);
for(j=0; j<frameNum; j++)
frames[j] = -1;
printf("\nReference String\t Page Frames\n");
for(k=0; k<pageNum; k++)
{
flag[k] = 0;
for(l=0; l<frameNum; l++)
{
if(frames[l] == pages[k])
{
flag[k] = 1;
break;
}
}
if(flag[k] == 1)
{
counter++;
continue;
}
if(counter < frameNum)
{
frames[counter] = pages[k];
counter++;
}
else
{
min = 9999;
for(l=0; l<frameNum; l++)
{
if(flag[l] < min)
{
min = flag[l];
j = l;
}
}
frames[j] = pages[k];
faults++;
}
printf("%d\t\t", pages[k]);
for(l=0; l<frameNum; l++)
printf("%d\t", frames[l]);
printf("\n");
for(l=0; l<frameNum; l++)
flag[l]++;
}
printf("\nTotal Page Faults: %d", faults);
return 0;
}
```
阅读全文