前幾天介紹到 Linux 的一個排程(Scheduling)系統服務叫做 sys_nice(),與 sys_nice() 相關的 system call service 是 sys_getpriority() 與 sys_setpriority(),不過在看 kernel code 前,我們應該先試著了解 getpriority() 與 setpriority() 二個 system call 的用法。
先來了解一下 getpriority() 的用途,GETPRIORITY(2):
SYNOPSIS #include <sys/time.h> #include <sys/resource.h> int getpriority(int which, int who);
getpriority() 的 which 參數用來指定要取得 priority 對象:process、process group 或 user ID。
最容易學習的方式就是讀範例,所以我們將會設計 2 個範例來執行。
which 參數:
實測結果
隨便找一個對象下手:
# ps ax ... 17349 ? S 0:02 [httpd] ...
把 PID 17349 的 scheduling priority 往上提升一級:
另外,系統指令 nice 可以用來設定執行命令的 process priority:# ./getpriority 17349 Process (17349) Priority is 0. # ./setpriority Usage: ./setpriority [pid] [priority (-20~19)] # ./setpriority 17349 -1 OK. # ./getpriority 17349 Process (17349) Priority is -1.
NICE(1) FSF NICE(1) NAME nice - run a program with modified scheduling priority SYNOPSIS nice [OPTION] [COMMAND [ARG]...] DESCRIPTION Run COMMAND with an adjusted scheduling priority. With no COMMAND, print the current scheduling priority. ADJUST is 10 by default. Range goes from -20 (highest priority) to 19 (lowest). -n, --adjustment=ADJUST increment priority by ADJUST first --help display this help and exit --version output version information and exit
程式碼
/* Program: getpriority.c */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> int main(int argc, char *argv[]) { /* getpriority() 傳回的類別是 int */ int prio_process, prio_pgroup, prio_user; pid_t pid; if (argc != 2) return -1; pid = atoi(argv[1]); prio_process = getpriority(PRIO_PROCESS, pid); printf("Process (%d) Priority is %d.\n", pid, prio_process); return 0; }
/* Program: setpriority.c */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> int main(int argc, char *argv[]) { int errno, prio; pid_t pid; if (argc != 3) { printf("Usage: %s [pid] [priority (-20~20)]\n", argv[0]); return -1; } pid = atoi(argv[1]); prio = atoi(argv[2]); errno = setpriority(PRIO_PROCESS, pid, prio); printf("OK.\n"); return 0; }了解 setpriority() 與 getpriority() 後,就可以開始研究 system call service - 'sys_setpriority' 與 'sys_getpriority' 了。
Jollen's Blog 使用 Github issues 與讀者交流討論。請點擊上方的文章專屬 issue,或 open a new issue
您可透過電子郵件 jollen@jollen.org,或是 Linkedin 與我連絡。更歡迎使用微信,請搜尋 WeChat ID:jollentw