计算机操作系统可变分区代码,操作系统实验一可变分区存储管理(含代码)
时间: 2023-08-06 21:26:07 浏览: 135
以下是一个简单的可变分区存储管理的代码示例,使用C语言编写:
```
#include<stdio.h>
#include<stdlib.h>
// 定义进程控制块结构体
typedef struct PCB {
int pid; // 进程ID
int size; // 占用内存大小
int start; // 起始地址
} PCB;
// 定义空闲分区结构体
typedef struct FreeBlock {
int size; // 分区大小
int start; // 起始地址
struct FreeBlock *next; // 指向下一个空闲分区
} FreeBlock;
FreeBlock *freeList; // 空闲分区链表
PCB *processTable[10]; // 进程控制块数组
int pidCount = 0; // 进程ID计数器
// 初始化空闲分区链表
void initFreeList(int size, int start) {
freeList = (FreeBlock*)malloc(sizeof(FreeBlock));
freeList->size = size;
freeList->start = start;
freeList->next = NULL;
}
// 查找合适的空闲分区
FreeBlock* findFreeBlock(int size) {
FreeBlock *prev = NULL;
FreeBlock *current = freeList;
while (current != NULL) {
if (current->size >= size) {
return current;
}
prev = current;
current = current->next;
}
return NULL;
}
// 分配空闲分区
void allocateMemory(int pid, int size) {
FreeBlock *block = findFreeBlock(size);
if (block == NULL) {
printf("No free block available for allocation.\n");
return;
}
PCB *process = (PCB*)malloc(sizeof(PCB));
process->pid = pid;
process->size = size;
process->start = block->start;
// 更新空闲分区链表
if (block->size == size) {
if (block == freeList) {
freeList = block->next;
} else {
FreeBlock *prev = freeList;
while (prev->next != block) {
prev = prev->next;
}
prev->next = block->next;
}
free(block);
} else {
block->start += size;
block->size -= size;
}
// 更新进程控制块数组
processTable[pid] = process;
printf("Process %d allocated %d bytes of memory from address %d.\n", pid, size, process->start);
}
// 释放已分配的空间
void freeMemory(int pid) {
PCB *process = processTable[pid];
FreeBlock *block = (FreeBlock*)malloc(sizeof(FreeBlock));
block->size = process->size;
block->start = process->start;
// 查找插入位置
FreeBlock *prev = NULL;
FreeBlock *current = freeList;
while (current != NULL && current->start < block->start) {
prev = current;
current = current->next;
}
// 插入空闲分区
if (prev == NULL) {
block->next = freeList;
freeList = block;
} else {
prev->next = block;
block->next = current;
}
// 更新进程控制块数组
processTable[pid] = NULL;
printf("Process %d freed %d bytes of memory from address %d.\n", pid, process->size, process->start);
free(process);
}
int main() {
// 初始化空闲分区链表
initFreeList(512, 0);
// 分配内存
allocateMemory(pidCount++, 100);
allocateMemory(pidCount++, 200);
allocateMemory(pidCount++, 50);
// 释放内存
freeMemory(1);
freeMemory(0);
allocateMemory(pidCount++, 150);
allocateMemory(pidCount++, 100);
return 0;
}
```
该代码实现了以下功能:
1. 初始化一个大小为512,起始地址为0的空闲分区链表。
2. 定义了进程控制块结构体和空闲分区结构体。
3. 实现了查找合适的空闲分区的函数。
4. 实现了分配空闲分区的函数,该函数会更新空闲分区链表和进程控制块数组。
5. 实现了释放已分配的空间的函数,该函数会插入一个空闲分区到空闲分区链表,并更新进程控制块数组。
6. 在主函数中测试了分配和释放内存的功能。