- 实验二:完成一个简单的时间片轮转多道程序内核代码
- 首先按照实验楼所指示的步骤进行实验,结果如下图所示:
- 上述实验代码仅包含时钟中断,并不涉及多道程序进程切换,下面进行代码修改,修改后的代码如下:
- 首先新增了一个名称为mypcb.h的头文件:
#define MAX_TASK_NUM 4
#define KERNEL_STACK_SIZE 1024*2
struct Thread {
unsigned long ip;
unsigned long sp;
};
typedef struct PCB{
int pid;
volatile long state;
unsigned long stack[KERNEL_STACK_SIZE];
struct Thread thread;
unsigned long task_entry;
struct PCB *next;
}tPCB;
void my_schedule(void);
- 然后对文件mymain.c进行修改:
#include#include #include #include #include #include "mypcb.h" tPCB task[MAX_TASK_NUM]; tPCB * my_current_task = NULL; volatile int my_need_sched = 0; void my_process(void); void __init my_start_kernel(void) { int pid = 0; int i; task[pid].pid = pid; task[pid].state = 0; task[pid].task_entry = task[pid].thread.ip = (unsigned long)my_process; task[pid].thread.sp = (unsigned long)&task[pid].stack[KERNEL_STACK_SIZE-1]; task[pid].next = &task[pid]; for(i=1;i pid); if(my_need_sched == 1){ my_need_sched = 0; my_schedule(); } printk(KERN_NOTICE "this is process %d +n",my_current_task->pid); } } }
- 最后对文件myinterrupt.c也进行了相应的修改:
#include#include #include #include #include #include "mypcb.h" extern tPCB task[MAX_TASK_NUM]; extern tPCB * my_current_task; extern volatile int my_need_sched; volatile int time_count = 0; void my_timer_handler(void){ #if 1 if(time_count%1000 == 0 && my_need_sched != 1){ printk(KERN_NOTICE ">>>my_timer_handler here<< next == NULL){ return; } printk(KERN_NOTICE ">>>my_schedule<< next; prev = my_current_task; if(next->state == 0){ my_current_task = next; printk(KERN_NOTICE ">>>switch %d to %d<< pid,next->pid); asm volatile( "pushl %%ebpnt"//将prev进程的EBP压入栈中 "movl %%esp,%0nt"//将当前ESP存入prev进程的thread.sp中,保存prev进程的栈顶 "movl %2,%%espnt"//将next进程的thread.sp栈顶存入ESP中 "movl $1f,%1nt"//将立即数1f存入prev进程的thread.ip中,下次调用prev进程时从该处开始执行指令 "pushl %3nt"//将next进程的thread.ip压栈 "retnt"//将next进程的thread.ip出栈,并存入EIP中,下一条指令从EIP即next进程的thread.ip所指指令开始执行,程序切换到next进程 "1:t" "popl %%ebpnt" : "=m" (prev->thread.sp),"=m" (prev->thread.ip) : "m" (next->thread.sp),"m" (next->thread.ip)); } return; }
- 实验分析
- 由于在上述除0号进程以外的进程初始化语句中省略了“ task[pid].state = -1”这条语句,使得所有进程初始化后的state均为runnable,即0,因此在进程切换函数my_schedule(void)中将if-else语句调整为if语句,以此来实现进程的切换。
- 程序初始化完毕后,首先执行0号进程,0号进程的入口地址为函数my_process();因此开始执行函数my_process();在0号进程执行过程中,函数my_timer_handler()会被内核调用,触发时钟中断,并当条件满足时,置my_need_sched=1,表示需要进行时间片轮转进程调度;之后在0号进程执行到if(i%10000000==0)若条件满足则会执行以下语句:
printk(KERN_NOTICE "this is process %d -n",my_current_task->pid);
if(my_need_sched == 1){
my_need_sched = 0;
my_schedule();
}
printk(KERN_NOTICE "this is process %d +n",my_current_task->pid);
- 之前my_timer_handler()已经将my_need_sched置为1,条件判断为真,则紧接着会执行“my_need_sched = 0;my_schedule();”这两条语句。首先使my_need_sched重新为0,防止当前时间片用完之前再次发生进程切换,当前时间片用完时再次置为1,然后调用函数my_schedule()进行进程的切换。
- 进程切换的详细过程如上述代码中的注释,当执行完指令"retnt"后,程序转入next进程中thread.ip所指的指令地址处开始执行指令,程序成功切换到了next进程;之后随着时间片轮转,程序还会像上述切换过程一样不停地进行进程之间的切换。
- 实验结果截图如下



