1 Process State and Scheduling
1.scheduler唯一的任务是决定哪个进程使用cpu
2 The O.S. Scheduler
2.1 O.S. Scheduling Ideas
- 一个好的scheduling algorithm必须满足以下三点
- CPU Utilization:cpu被充分利用
- Turnaround Time:进程的周转时间,一个进程运行多长时间
- Fairness:平等,所有的进程优先权相同
2.2 Preemptive Scheduling
- 所有进程交替执行
- 但是如果有等待IO的进程,就会浪费时间
2.3 Priority Queue Scheduling
- unix使用混合的 round-robin scheduling and priority scheduling,既 multilevel queue scheduling
- 所有的进程交替执行,进行被选择执行的条件时优先权
2.3.1 How nice a program is its priority
- priority优先权最低是-20,very mean,最高是19,very nice
- 所有的进程优先权是0
- 鼠标移动的进程优先权要高
- 守护进程的优先权低,不影响用户
2.3.2 Viewing Process State with ps
ps axo nice,comm,pid --sort nice
2.3.3 Programming Priority with getpriority() and nice()
/*getpriority.c*/
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/resource.h>
int main(){
int prio;
prio = getpriority(PRIO_PROCESS, 0); //get the priority of this process
printf("Priority: %d\n",prio);
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/resource.h>
int main(){
int prio;
prio = getpriority(PRIO_PROCESS, 0); //get the priority of this process
printf("Priority: %d\n",prio);
if( nice(10) != 10){ //error checking is different
perror("nice");
return 1;
}
prio = getpriority(PRIO_PROCESS, 0); //get the priority of this process
printf("Priority: %d\n",prio);
return 0;
}
3 Process States
- OS需要综合考虑both the priority of a process and if it ready to run in order to maximize the utilization of the CPU
3.1 Running, Waiting, Blocked, and Undead
- 三种主要的状态
- running 正在cpu上运行
- ready and waiting 一旦被选中就会运行
- blocked and waiting 需要等待其他信息完成,才能运行,比如等待I/O,比如父进程等待子进程
3.2 Undead processes: Zombies
- 僵尸进程概念
- 父进程创建了子进程
- 子进程退出
- 父进程没有
wait
子进程,且没有退出 - 父进程和这些子进程都统称为僵尸进程
ps -o pid,comm,state
查看僵尸进程
/*zombies.c*/
int main(){
int i;
for(i=0; i<10;i++){
if(fork() == 0){ //create a child
_exit(0); // and exit
}
}
while(1); //run forever
}
3.3 Orphan Process, init, and daemons
- 孤儿进程
- 父进程死,子进程被init继承领养
- init进程调用wait等待这些子进程
- shell中用
d.
标识,既daemon
,daemon
进程在父进程死后,会被init领养,继续存活
参考:
https://www.usna.edu/Users/cs/aviv/classes/ic221/s16/lec/15/lec.html#coderef-bad_ref