现在需要维护系统中的空闲页框数,你需要 - 在`kalloc.c`文件中定义一个全局变量`freeMemCnt`,记录空闲页框数; - 在分配和回收内存时维护这个全局变量; - 然后实现系统调用`int freemem(void)`查询这个变量的值; - 实现以下用户命令`free`,打印空闲页框数。int main(int argc, char **argv) { printf(1,"# of free frames is %d\n",freeMem()); if(fork()==0){ printf(1,"Child, # of free frames is %d\n",freeMem()); }else{ wait(); printf(1,"parent: # of free frames is %d\n",freeMem()); } exit(); }
时间: 2024-01-15 17:05:38 浏览: 403
好的,那么在 `kalloc.c` 中添加全局变量 `freeMemCnt`,并在分配和回收内存时维护这个变量的代码如下:
```c
#include "defs.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "spinlock.h"
#include "proc.h"
#include "x86.h"
static struct run {
struct run *next;
} *kfreelist;
static uint freeMemCnt = 0; // 新增全局变量
void
kinit1(void *vstart, void *vend)
{
kfreelist = 0;
char *p;
p = (char*)PGROUNDUP((uint)vstart);
for(; p + PGSIZE <= (char*)vend; p += PGSIZE) {
kfree(p);
}
}
void
kfree(char *v)
{
struct run *r;
if((uint)v % PGSIZE || v < end || V2P(v) >= PHYSTOP)
panic("kfree");
// Acquire the lock on kfreelist
acquire(&kmem.lock);
// Add the memory block to kfreelist
r = (struct run*)v;
// 维护 freeMemCnt 变量
freeMemCnt++;
r->next = kfreelist;
kfreelist = r;
// Release the lock on kfreelist
release(&kmem.lock);
}
char*
kalloc(void)
{
struct run *r;
// Acquire the lock on kfreelist
acquire(&kmem.lock);
// Get a memory block from kfreelist
r = kfreelist;
if(r)
kfreelist = r->next;
// 维护 freeMemCnt 变量
if (freeMemCnt > 0) {
freeMemCnt--;
}
// Release the lock on kfreelist
release(&kmem.lock);
return (char*)r;
}
```
然后在 `syscall.h` 中定义 `freemem` 系统调用的宏定义:
```c
#define SYS_freemem 23
```
在 `syscall.c` 中添加 `sys_freemem` 系统调用的函数实现:
```c
extern int sys_freemem(void);
static int (*syscalls[])(void) = {
...
[SYS_freemem] sys_freemem,
...
};
int
sys_freemem(void)
{
return freeMemCnt;
}
```
在 `usys.S` 中添加 `freemem` 系统调用的汇编实现:
```assembly
SYSCALL(freemem)
```
最后,在用户空间编写 `free.c` 程序,实现以下用户命令 `free`:
```c
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
int
main(int argc, char *argv[])
{
printf("Free page frames: %d\n", freemem());
exit(0);
}
```
最后,再使用以下代码测试一下:
```c
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
int
main(int argc, char **argv)
{
printf(1, "# of free frames is %d\n", freemem());
if (fork() == 0) {
printf(1, "Child, # of free frames is %d\n", freemem());
} else {
wait();
printf(1, "Parent: # of free frames is %d\n", freemem());
}
exit(0);
}
```
阅读全文