操作系统是如何工作的?
秦鼎涛 《Linux内核分析》MOOC课程http://mooc.study.163.com/course/USTC-1000029000
一、实验二:完成一个简单的时间片轮转多道程序内核代码(实验楼截图)




二、进程的启动和进程的切换机制
1、多道进程的处理采用了中断机制,利用cpu和内核代码来实现保存现场和回复现场。本次课程的实验平台模拟了一个时间片轮转多道程序的系统。
2、时间片轮转多道程序代码:
| /* | |
| * linux/mykernel/myinterrupt.c | |
| * | |
| * Kernel internal my_timer_handler | |
| * | |
| * 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" | |
| extern tPCB task[MAX_TASK_NUM]; |
|
| extern tPCB * my_current_task; |
|
| extern volatile int my_need_sched; |
|
| volatile int time_count = 0; | |
| /* | |
| * Called by timer interrupt. | |
| * it runs in the name of current running process, | |
| * so it use kernel stack of current running process | |
| */ | |
| void my_timer_handler(void) | |
| { | |
| #if 1 | |
| if(time_count%1000 == 0 && my_need_sched != 1) | |
| { | |
| printk(KERN_NOTICE ">>>my_timer_handler here<<<\n"); | |
| my_need_sched = 1; | |
| } | |
| time_count ++ ; | |
| #endif | |
| return; | |
| } | |
| void my_schedule(void) | |
| { | |
| tPCB * next; | |
| tPCB * prev; | |
| if(my_current_task == NULL | |
| || my_current_task->next == NULL) | |
| { | |
| return; | |
| } | |
| printk(KERN_NOTICE ">>>my_schedule<<<\n"); | |
| /* schedule */ | |
| next = my_current_task->next; | |
| prev = my_current_task; | |
| if(next->state == 0)/* -1 unrunnable, 0 runnable, >0 stopped */ | |
| { | |
| /* switch to next process */ | |
| 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) | |
| ); | |
| my_current_task = next; | |
| printk(KERN_NOTICE ">>>switch %d to %d<<<\n",prev->pid,next->pid); | |
| } | |
| else | |
| { | |
| next->state = 0; | |
| my_current_task = next; | |
| printk(KERN_NOTICE ">>>switch %d to %d<<<\n",prev->pid,next->pid); | |
| /* switch to new process */ | |
| asm volatile( | |
| "pushl %%ebp\n\t" /* save ebp */ | |
| "movl %%esp,%0\n\t" /* save esp */ | |
| "movl %2,%%esp\n\t" /* restore esp */ | |
| "movl %2,%%ebp\n\t" /* restore ebp */ | |
| "movl $1f,%1\n\t" /* save eip */ | |
| "pushl %3\n\t" | |
| "ret\n\t" /* restore eip */ | |
| : "=m" (prev->thread.sp),"=m" (prev->thread.ip) | |
| : "m" (next->thread.sp),"m" (next->thread.ip) | |
| ); | |
| } | |
| return; | |
| } | |
三、总结:
课程中提到了计算机工作的三大法宝:存储程序计算机工作模型、堆栈、中断。
-
存储程序计算机工作模型,简单的说就是CPU解释并执行计算机指令,Memory用来存储数据和程序。
-
堆栈机制(函数调用堆栈),在机器语言和汇编语言的时候并不那么重要,后来有了高级语言,尤其是函数调用使得堆栈成为计算机工作的重要基础;
-
中断,引入中断机制使内核可以处理硬件外设I/O。中断来源有I/O请求、时钟以及系统调用。中断可以使计算机同时处理多个程序,提高了计算机效率。
浙公网安备 33010602011771号