在多任务操作系统中(Linux就是),内核负责将CPU时间分配给系统上运行的每个进程。调 度优先级(scheduling priority)是内核分配给进程的CPU时间(相对于其他进程)。
在Linux系统 中,由shell启动的所有进程的调度优先级默认都是相同的。
调度优先级是个整数值,从-20(最高优先级)到+19(最低优先级)。默认情况下,bash shell 以优先级0来启动所有进程。
窍门:
最低值-20是最高优先级,而最高值19是最低优先级,这太容易记混了。只要记住那句俗 语“好人难做”就行了。越是“好”或高的值,获得CPU时间的机会越低(谦让度越高,让出的执行机会越多,也就执行的越慢)
nice命令的-n选项并不是必须的,只需要在破折号后面跟上优先级就行了。(例如:nice -10 ./test4.sh)
bash shell 以优先级0来启动所有进程,谦让度默认都为零
macname@localhost Desktop % ./test.sh Loop #1 Loop #2 Loop #3 Loop #4 Loop #5 ^Z zsh: suspended ./test.sh macname@localhost Desktop % jobs -l [1] + 49332 suspended ./test.sh macname@localhost Desktop % macname@localhost Desktop % ps -p 49332 -o pid,ppid,ni PID PPID NI 49332 40368 0 macname@localhost Desktop % macname@localhost Desktop % bg [1] + continued ./test.sh Loop #6 macname@localhost Desktop % Loop #7 Loop #8 fgLoop #9 [1] + running ./test.sh Loop #10 Loop #11 Loop #12 ^CGoodbye...
设置谦让度为10
macname@localhost Desktop % macname@localhost Desktop % nice -n 10 ./test.sh Loop #1 Loop #2 Loop #3 ^Z zsh: suspended nice -n 10 ./test.sh macname@localhost Desktop % jobs -l [1] - 49813 suspended sudo nice -n -10 ./test.sh [2] + 51107 suspended nice -n 10 ./test.sh macname@localhost Desktop % macname@localhost Desktop % ps -p 51107 -o pid,ppid,ni PID PPID NI 51107 40368 10 macname@localhost Desktop %
普通用户,降低谦让度,会提示权限不够
macname@localhost Desktop % nice -n -10 ./test.sh nice: setpriority: Permission denied Loop #1 Loop #2 Loop #3 Loop #4 ^Z zsh: suspended nice -n -10 ./test.sh macname@localhost Desktop % jobs -l [1] + 51326 suspended nice -n -10 ./test.sh macname@localhost Desktop % ps -p 51326 -o pid,ppid,ni PID PPID NI 51326 40368 0 macname@localhost Desktop %
管理员降低谦让度,最低为0
macname@localhost Desktop % sudo nice -n -10 ./test.sh Password: Loop #1 Loop #2 Loop #3 Loop #4 ^Z zsh: suspended sudo nice -n -10 ./test.sh macname@localhost Desktop % jobs -l [1] + 49813 suspended sudo nice -n -10 ./test.sh macname@localhost Desktop % ps -p 49813 -o pid,ppid,ni PID PPID NI 49813 40368 0 macname@localhost Desktop %