编写一段C程序,在一个请求分页系统中,假如一个作业的页面走向为:1,2,3,4,1,2,5,1,2,3,4,5。当分配给该作业的物块数为3,分别采用先进先出算法(FIFO) 、最佳淘汰算法(OPT)、最近最少使用算法(LRU),
时间: 2024-03-18 17:35:26 浏览: 102
以下是C语言实现请求分页系统中三种算法的代码:
1. 先进先出算法(FIFO)
```c
#include <stdio.h>
#define MAX 3
int main()
{
int pages[] = {1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5};
int frames[MAX], faults = 0, pointer = 0, flag1, flag2, i, j, k;
for(i = 0; i < MAX; ++i)
frames[i] = -1;
for(i = 0; i < 12; ++i)
{
flag1 = flag2 = 0;
for(j = 0; j < MAX; ++j)
{
if(frames[j] == pages[i])
{
flag1 = flag2 = 1;
break;
}
}
if(flag1 == 0)
{
frames[pointer] = pages[i];
++pointer;
++faults;
if(pointer == MAX)
pointer = 0;
}
printf("\n");
for(j = 0; j < MAX; ++j)
printf("%d\t", frames[j]);
}
printf("\n\nTotal Page Faults = %d", faults);
return 0;
}
```
2. 最佳淘汰算法(OPT)
```c
#include <stdio.h>
#define MAX 3
int main()
{
int pages[] = {1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5};
int frames[MAX], faults = 0, flag1, flag2, flag3, i, j, k, pos, max;
for(i = 0; i < MAX; ++i)
frames[i] = -1;
for(i = 0; i < 12; ++i)
{
flag1 = flag2 = 0;
for(j = 0; j < MAX; ++j)
{
if(frames[j] == pages[i])
{
flag1 = flag2 = 1;
break;
}
}
if(flag1 == 0)
{
for(j = 0; j < MAX; ++j)
{
if(frames[j] == -1)
{
frames[j] = pages[i];
++faults;
flag2 = 1;
break;
}
}
}
if(flag2 == 0)
{
flag3 = 0;
for(j = 0; j < MAX; ++j)
{
pos = 0;
for(k = i + 1; k < 12; ++k)
{
if(frames[j] == pages[k])
{
if(k > pos)
{
pos = k;
flag3 = 1;
}
}
}
if(flag3 == 0)
{
pos = j;
break;
}
}
frames[pos] = pages[i];
++faults;
}
printf("\n");
for(j = 0; j < MAX; ++j)
printf("%d\t", frames[j]);
}
printf("\n\nTotal Page Faults = %d", faults);
return 0;
}
```
3. 最近最少使用算法(LRU)
```c
#include <stdio.h>
#define MAX 3
int main()
{
int pages[] = {1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5};
int frames[MAX], faults = 0, flag1, flag2, flag3, i, j, k, pos, max, counter[MAX];
for(i = 0; i < MAX; ++i)
{
frames[i] = -1;
counter[i] = 0;
}
for(i = 0; i < 12; ++i)
{
flag1 = flag2 = 0;
for(j = 0; j < MAX; ++j)
{
if(frames[j] == pages[i])
{
counter[j] = 1;
flag1 = flag2 = 1;
break;
}
}
if(flag1 == 0)
{
for(j = 0; j < MAX; ++j)
{
if(counter[j] == 0)
{
pos = j;
flag2 = 1;
break;
}
}
if(flag2 == 0)
{
max = counter[0];
pos = 0;
for(j = 1; j < MAX; ++j)
{
if(counter[j] > max)
{
max = counter[j];
pos = j;
}
}
}
frames[pos] = pages[i];
++faults;
for(j = 0; j < MAX; ++j)
counter[j]++;
counter[pos] = 0;
}
printf("\n");
for(j = 0; j < MAX; ++j)
printf("%d\t", frames[j]);
}
printf("\n\nTotal Page Faults = %d", faults);
return 0;
}
```
阅读全文