欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

先进先出(FIFO)虚拟存储管理页面淘汰算法(C)

程序员文章站 2022-03-14 15:31:20
...
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int indexOf(char *s, char c, int len) {
    for (int i = 0; i < len; i++) {
        if (s[i] == c) {
            return i;
        }
    }

    return -1;
}

void moveForward(char *s, char c, int len) {
    len--;
    for (int i = 0; i < len; i++) {
        s[i] = s[i + 1];
    }
    s[len] = c;
}

void main() {
    // 进程允许拥有的页数
    int pages;
    // 页面访问字符串
    char s[100];
    printf("Number of pages allowed by the process: ");
    scanf("%d", &pages);
    printf("Please enter an access string: ");
    scanf("%s", s);


    char memory[pages];
    // 缺页次数
    int times = 0;
    int index = 0;

    for (int i = 0, len = strlen(s); i < len; i++) {
        char c = s[i];
        if (index < pages) {
            if (indexOf(memory, c, pages) == -1) {
                memory[index] = c;
                index++;
                times++;
            }
        } else {
            if (indexOf(memory, c, pages) == -1) {
                printf("eliminate %c \n", memory[0]);
                moveForward(memory, c, pages);
                times++;
            }
        }
    }
    printf("Total number of page missing: %d", times);
}