linux系统内核流转浅析
本站寻求有缘人接手,详细了解请联系站长QQ1493399855
SJTUBEAR 原创作品转载请注明出处 《Linux内核分析》MOOC课程http://mooc.study.163.com/course/USTC-1000029000
我们通过简单地内核来模拟一下linux的系统调度,代码如下:
/** linux/mykernel/mymain.c** Kernel internal my_start_kernel** Copyright (C) 2013 Mengning**/ #include <linux/types.h> #include <linux/string.h> #include <linux/ctype.h> #include <linux/tty.h> #include <linux/vmalloc.h>#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;/* Initialize process 0*/task[pid].pid = pid;task[pid].state = 0;/* -1 unrunnable, 0 runnable, >0 stopped */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];/*fork more process */for(i=1;i<MAX_TASK_NUM;i++){memcpy(&task[i],&task[0],sizeof(tPCB));task[i].pid = i;task[i].state = -1;task[i].thread.sp = (unsigned long)&task[i].stack[KERNEL_STACK_SIZE-1];task[i].next = task[i-1].next;task[i-1].next = &task[i];}/* start process 0 by task[0] */pid = 0;my_current_task = &task[pid];asm volatile("movl %1,%%esp " /* set task[pid].thread.sp to esp */"pushl %1 " /* push ebp */"pushl %0 " /* push task[pid].thread.ip */"ret " /* pop task[pid].thread.ip to eip */"popl %%ebp ": : "c" (task[pid].thread.ip),"d" (task[pid].thread.sp) /* input c or d mean %ecx/%edx*/); } void my_process(void) {int i = 0;while(1){i++;if(i%10000000 == 0){printk(KERN_NOTICE "this is process %d - ",my_current_task->pid);if(my_need_sched == 1){my_need_sched = 0;my_schedule();}printk(KERN_NOTICE "this is process %d + ",my_current_task->pid);} } }