(源:http://blog.sina.com.cn/s/blog_596f35310100aukf.html)
nice函数
功能描述:
用法:
返回说明:
范例:
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
int main()
{
}
getpriority() 與 setpriority() 程式設計
SYNOPSIS
getpriority() 的 which 參數用來指定要取得 priority 對象:process、process group 或 user ID。
最容易學習的方式就是讀範例,所以我們將會設計 2 個範例來執行。
which 參數:
- PRIO_PROCESS:who 參數指定 process ID,傳回 process 的 priority。
- PRIO_PGRP:who 參數指定 process group ID,傳回 process group 的 priority。
- PRIO_USER:who 參數指定 user ID,傳回 user 的 priority 。
Jollen 寫了二個程式:setpriority.c 與 getpriority.c。先來測試一下。
實測結果
隨便找一個對象下手:
# ps ax ... 17349 ? S 0:02 [httpd] ...
把 PID 17349 的 scheduling 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 可以用來設定執行命令的 process priority:
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
程式碼
#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 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; }
#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,nice |
表头文件
| #include<sys/time.h> #include<sys/resource.h> |
定义函数
| int setpriority(int which,int who, int prio); |
函数说明
| setpriority()可用来设置进程、进程组和用户的进程执行优先权。参数which有三种数值,参数who 则依which值有不同定义 进程默认的优先权都为0,所以每个进程执行所占用的时间都差不多。为了使某个进程执行的时间更长一些,可以提高该进程的优先权。 |
返回值
| 执行成功则返回0,如果有错误发生返回值则为-1,错误原因存于errno。 ESRCH 参数which或who 可能有错,而找不到符合的进程 EINVAL 参数which值错误。 EPERM 权限不够,无法完成设置 EACCES 一般用户无法降低优先权 |