写一个C语言代码采用最近最久未使用置换算法LRU。输入给定的页面访问序列和内存的物理块数下,输出缺页率。 二、实验测试: 【输入】 虚页的个数N:8 //(虚页序号0--7) 虚页访问次数num:20 页面访问序列:7 0
时间: 2023-11-28 16:49:03 浏览: 80
以下是采用最近最久未使用置换算法LRU的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main()
{
int N, num, i, j, k, page_faults = 0;
int pages[MAX], frames[MAX], counter[MAX];
int flag1, flag2, pos, max;
printf("Enter the number of pages: ");
scanf("%d", &N);
printf("Enter the number of page accesses: ");
scanf("%d", &num);
printf("Enter the page reference string: ");
for(i=0; i<num; i++)
scanf("%d", &pages[i]);
printf("Enter the number of physical memory frames: ");
scanf("%d", &k);
for(i=0; i<k; i++)
{
frames[i] = -1;
counter[i] = 0;
}
for(i=0; i<num; i++)
{
flag1 = flag2 = 0;
for(j=0; j<k; j++)
{
if(frames[j] == pages[i])
{
counter[j] = 1;
flag1 = flag2 = 1;
break;
}
}
if(flag1 == 0)
{
for(j=0; j<k; j++)
{
if(frames[j] == -1)
{
page_faults++;
frames[j] = pages[i];
counter[j] = 1;
flag2 = 1;
break;
}
}
}
if(flag2 == 0)
{
for(j=0; j<k; j++)
counter[j]++;
max = counter[0];
pos = 0;
for(j=1; j<k; j++)
{
if(counter[j] > max)
{
max = counter[j];
pos = j;
}
}
frames[pos] = pages[i];
counter[pos] = 1;
page_faults++;
}
printf("Page reference string: ");
for(j=0; j<=i; j++)
printf("%d ", pages[j]);
printf("\nFrame Status: ");
for(j=0; j<k; j++)
{
if(frames[j] == -1)
printf("X ");
else
printf("%d ", frames[j]);
}
printf("\n");
}
printf("Total number of page faults: %d\n", page_faults);
printf("Page Fault Rate: %.2f\n", (float)page_faults/num);
return 0;
}
```
输入示例:
```
Enter the number of pages: 8
Enter the number of page accesses: 2
Enter the page reference string: 7 0
Enter the number of physical memory frames: 3
```
输出示例:
```
Page reference string: 7
Frame Status: 7 X X
Page reference string: 7 0
Frame Status: 7 0 X
Total number of page faults: 2
Page Fault Rate: 1.00
```
阅读全文