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; }