记得有个老师曾经说过:操作系统就是躺在内存里等待被调用的代码。我觉得说的是有一定道理的。计算机有三大法宝:程序存储计算机,堆栈,中断。中断无疑是操作系统的基础之一。中断发生,系统从用户态变为内核态,然后执行内核代码。
1.1首先看my_pcb.h里面的内容:
struct Thread {
unsigned longip;
unsigned longsp;
};
typedef struct PCB{
int pid;
volatile long state;/* -1 unrunnable, 0 runnable, >0 stopped */
char stack[KERNEL_STACK_SIZE];
/* CPU-specific state of this task */
struct Thread thread;
unsigned longtask_entry;
struct PCB *next;
}tPCB;
这里面定义了pcb,描述了进程的信息,包括pid号,进程状态,内核栈,程序入口,下一个程序指针,ip和sp的指针。每个进程都有自己唯一的pcb,操作系统正是根据pcb对进程予以调度。
1.2在看mymain.c里面的内容:
首先对PCB进行初始化:
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
{
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];
}
然后是关键代码:
asm volatile(
"movl %1,%%esp\n\t" /* set task[pid].thread.sp to esp */
"pushl %1\n\t" /* push ebp */
"pushl %0\n\t" /* push task[pid].thread.ip */
"ret\n\t" /* pop task[pid].thread.ip to eip */
"popl %%ebp\n\t"
:
: "c" (task[pid].thread.ip),"d" (task[pid].thread.sp)/* input c or d mean %ecx/%edx*/
);
这段汇编代码完成了0号进程的第一次启动。关键是ret这个地方,因为不能直接改变eip的值,所以先将ip压入栈中,然后ret执行,就会将栈中程序入口弹出,并赋给eip,这样,程序就会跳转到myprocess程序。
在看my_process: void my_process(void)
{
int i = 0;
while(1)
{
i++;
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_need_sched==1时,发生调度。my_need_sched的值是在time_handler里面改变的。发生时钟中断,就进入time_handler函数。
然后是进程调度的关键代码:
asm volatile(
"pushl %%ebp\n\t" /* save ebp */
"movl %%esp,%0\n\t" /* save esp */
"movl %2,%%esp\n\t" /* restore esp */
"movl $1f,%1\n\t" /* save eip */
"pushl %3\n\t"
"ret\n\t" /* restore eip */
"1:\t" /* next process start here */
"popl %%ebp\n\t"
: "=m" (prev->thread.sp),"=m" (prev->thread.ip)
: "m" (next->thread.sp),"m" (next->thread.ip)
);
首先保存当前进程的现场,然后恢复下一个进程的现场。类似,创建一个新进程,也是类似的道理。
总结:通过这次实验,对linux进程的调度有了更深的了解。