getpriority和setpriority

版权声明:本文为博主原创文章,遵循 CC 4.0 BY 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44880138/article/details/102619208

name

getpriority, setpriority - get/set program scheduling priority

function

int getpriority(int which, int who);
int setpriority(int which, int who, int prio);

Description

The scheduling priority of the process, process group, or user, as indicated by which and who is obtained with the getpriority() call and set with the setpriority() call.

The value which is one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and who is interpreted relative to which (a process identifier forPRIO_PROCESS, process group identifier forPRIO_PGRP, and a user ID for PRIO_USER). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process. Prio is a value in the range -20 to 19 (but see the Notes below). The default priority is 0; lower priorities cause more favorable scheduling.

The getpriority() call returns the highest priority (lowest numerical value) enjoyed by any of the specified processes. The setpriority() call sets the priorities of all of the specified processes to the specified value. Only the superuser may lower priorities.

Return Value

Since getpriority() can legitimately return the value -1, it is necessary to clear the external variable errno prior to the call, then check it afterward to determine if -1 is an error or a legitimate value. The setpriority() call returns 0 if there is no error, or -1 if there is.


setpriority 用来设置进程的优先级别的

int setpriority(int which, int who, int prio);
参数 which的不同时who代表的意思也不一样 :
PRIO_PROCESS 		who为进程的ID
PRIO_PGRP			who为进程组ID
PRIO_USER  			who为用户ID

参数prio
介于-20 至20 之间. 代表进程执行优先权, 数值越低代表有较高的优先次序, 执行会较频繁. 此优先权默认是0, 而只有超级用户 (root)允许降低此值

返回值:

执行成功则返回0, 如果有错误发生返回值则为-1, 错误原因存于errno.
1、ESRCH:参数which 或who 可能有错, 而找不到符合的进程
2、EINVAL:参数which 值错误.
3、EPERM:权限不够, 无法完成设置
4、EACCES:一般用户无法降低优先权

例子

// 设置该进程ID的优先级为-20(最高),经常被使用的
 pid_t pid = getpid();
 if (setpriority(PRIO_PROCESS, pid, -20)) // -20到20 越小优先级越高
   {
       fprintf(stderr, "Warning: Failed to set priority: %s\n",strerror(errno));
   }

getpriority()用来获取进程、进程组和用户的进程执行优先权。

int getpriority(int which, int who);
参数 which的不同时who代表的意思也不一样 :
PRIO_PROCESS 		who为进程的ID
PRIO_PGRP			who为进程组ID
PRIO_USER  			who为用户ID

返回值
出错就返回-1.
正常就返回 setprority()设置的优先级(-20到20之间),错误原因存在errno中。

注意:使用前建议清理一下errno

在errno中的错误

1、ESRCH:参数which 或who 可能有错, 而找不到符合的进程
2、EINVAL:参数which 值错误.
3、EPERM:权限不够, 无法完成设置
4、EACCES:一般用户无法降低优先权

猜你喜欢

转载自blog.csdn.net/weixin_44880138/article/details/102619208