当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
内核总结之进程和进程的调度
发布时间:2010/9/28 16:20:47 来源:城市学习网 编辑:ziteng
  进程就是资源的集合体,既包括打开的文件,收到的信号,占用的地址空间这些软资源,也包括对cpu,内存的占用这些硬资源。而线程只是代码的一个执行流,与其他线程共享某些资源。
  调度算法的设计目标,让cpu上的指令流更有价值,这就需要,
  1,调度必须尽可能快的完成,占用尽可能少的cpu时间
  2,交互进程尽快得到响应
  3,批处理进程尽快的处理完成
  这就需要调度算法在尽量短的时间内选出the most valueable的进程,也就是优先级最高的进程。并进行进程的切换,并且,进程切换的开销应尽可能小,主要包括页表的切换和寄存器的切换。
  在内核中用task_struct 来描述一个进程,
  struct task_struct{
  1082     int lock_depth;     /* BKL lock depth */
  1129     struct mm_struct *mm, *active_mm;
  1215 /* CPU-specific state of this task */
  1216     struct thread_struct thread;
  1217 /* filesystem information */
  1218     struct fs_struct *fs;
  1219 /* open file information */
  1220     struct files_struct *files;
  1221 /* namespaces */
  1222     struct nsproxy *nsproxy;
  1223 /* signal handlers */
  1224     struct signal_struct *signal;
  1225     struct sighand_struct *sighand;
  1226
  1227     sigset_t blocked, real_blocked;
  1228     sigset_t saved_sigmask; /* restored if set_restore_sigmask() was used */
  1229     struct sigpending pending;
  }
  current宏对当前任务的索引是通过sp找到thread_info,再通过thread_info的task字段找到当前任务
  struct thread_info
  {
  struct task_struct  *task;      /* main task structure */
  int         preempt_count;  /* 0 => preemptable,
  }
  do_fork()
  主要的工作由copy_process()完成
  This creates a new process as a copy of the old one, but does not actually start it yet.It copies the registers, and all the appropriate parts of the process environment.
  p = dup_task_struct(current);   为子进程分配task_struct和内核stack.
  然后copy_files(),copy_fs()进行拷贝。
  copy_thread,把用户传进来的通用寄存器进行拷贝给子进程并设置,这儿很关键
  childregs = task_pt_regs(p);
  *childregs = *regs;
  childregs->eax = 0;
  childregs->esp = esp;
  p->thread.esp = (unsigned long) childregs;
  p->thread.esp0 = (unsigned long) (childregs+1);
  p->thread.eip = (unsigned long) ret_from_fork;
  可见传入的用户态通用寄存器附给了子进程,并置eax=0所以返回的pid是0,估计是pt_regs里esp可能是无效的,(进入内核态时sp没有保存在pt_regs里),所以单独赋值了。task_struct的thread字段记录了进程特定于cpu的信息,但切换到子进程的时候,就把thread中esp,eip弹出,所以子进程就可以通过ret_from_fork返回运行了。
  而ret_from_fork
  asmlinkage void ret_from_fork(void) __asm__("ret_from_fork");
  不明白。
  所谓创建一个进程,就是分配合适的pid,并为之创建task_struct和内核stack,并把stack里的pt_regs设置下,返回的时候好恢复到调用点,并选择性的继承父进程的资源。
  schedule()
  1,通过o(1)算法选出优先级最高的进程。
  每个cpu有一个run_queue结构,保存有进程优先级的位图,通过位图索引到对应的list,取链首进程。
  2,switch_context()调用switch_mm()切换页表,switch_to()从上一个进程的处理器状态切换到新进程,包括保存恢复栈信息和寄存器信息
  内核的抢占性
  thread_info结构中的preemt_count字段表明当前进程是否可以被抢占
  24 #define preempt_count() (current_thread_info()->preempt_count)
  30 #define preempt_disable() \
  31 do { \
  32     inc_preempt_count(); \
  33     barrier(); \
  34 } while (0)
  内核的抢占点
  1,中断处理程序返回内核空间
  2,内核代码再次有可抢占性,如释放一个锁
  3,显示调用schedule,kernel trust kernel code,由调用者保证代码可以安全的被抢占
  4,内核中的任务阻塞,隐式调用schedule()
  对应的用户空间的抢占发生在
  1,系统调用返回
  2,中断处理返回到用户空间
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved