int getpriority(int which, int who);返回一组进程的优先级
参数which和who确定返回哪一组进程的优先级
The value which is one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER,
and who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and auser ID for PRIO_USER).
1、PRIO_PROCESS,一个特定的进程,此时who的取值为进程ID
2、PRIO_PGRP,一个进程组的所有进程,此时who的取值为进程组的ID
3、PRIO_USER,一个用户拥有的所有进程,此时who的取值为实际用户ID
getpriority如果出错返回-1,并且设置errno的值,errno的值可能是:
EINVAL which was not one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER.。which是一个无效的值
ESRCH No process was located using the which and who values specified.。which和who的组合与现存的所有进程均不匹配
注意:当指定的一组进程有不同优先级时,getpriority将返回其中优先级最低的一个。此外,当getpriority返回-1时,可能发生错误,
也有可能是返回的是指定进程的优先级。区分他的方法是,在调用getpriority前将errno清零。如果返回-1且errno不为零,说明有错误产生。
=============================================
调用nice来设置进程的优先级。
nice系统调用等同于:
int nice( int increment)
{
int oldprio = getpriority( PRIO_PROCESS, getpid());
return setpriority(PRIO_PROCESS, getpid(), oldprio + increment);
}
参数increment数值越大则优先顺序排在越后面, 即表示进程执行会越慢.
只有超级用户才能使用负的increment值, 代表优先顺序排在前面, 进程执行会较快.
#include <stdio.h> #include <unistd.h> #include <sys/time.h> #include <sys/resource.h> #include <stdlib.h> int main() { pid_t pid; int stat_val; int prio; int inc = 3; int exit_code; pid = fork(); if (0 == pid) { exit_code = 11; prio = getpriority(PRIO_PROCESS, getpid()); printf("the child's priority is:%d\n", prio); nice( inc ); prio = getpriority(PRIO_PROCESS, getpid()); printf("after nice(%d), the child's priority is:%d\n", inc, prio); printf("child will exit with the exit code:%d\n", exit_code); exit(exit_code); } else if (pid < 0) { exit(0); } wait(&stat_val); if ( WIFEXITED(stat_val) ) { printf("the child has exited, the exit code is:%d\n", WEXITSTATUS(stat_val)); } return 0; }