linux下进程优先级编程

//getprority()和setpriority都包含在这个文件当中
/*

1    nice 命令在头文件unistd.h当中,引用是把这个头文件包括在其中,这个函数只有超级用户才能使用,可以使用出错检测 
原型:  
#include<unistd.h>
int nice (int _inc)   _inc 为谦让值(-20~19)
返回值:
0 :调用成功
-1: 表示出错,可以察看errno获取出错信息

2    setpriority()这个函数可以设置其他进程的NI值,这个函数调用成功的情况是1)超级用户 2)修改用户的进程 ;其他用户调用是会出错
原型:
#include<sys/resource.h>
int setpriority(_priority_which_t _which, id_t _who, int _prio)
解释:
_which :可以为PRIO_PROCESS(设置自己的进程),PRIO_PGRP(设置某一进程组的谦让度),PRIO_USER(为某个用户的所有进程设置谦让度)
_who   :针对PRIO_PROCESS则是进程的ID号,PRIO_PGRP则是进程组的ID号,PRIO_USER则是用户的ID号
_prio  :谦让度 (-20~19)

3     getpriority()  这个函数雷同与setpriority()函数
原型:
#include<sys/resource.h>
int getpriority(_priority_which_t _which,id_t _who);
但是getpriority系统调用比较特殊,可能返回负值,就无法和出错区别,可以通过在调用前使errno置0,然后在进行判断

*/
#include<unistd.h>
#include<sys/resource.h>
#include<errno.h>
#include<stdio.h>


int main()
{

	int nPr;
	pid_t firefox=2076;//这个是我测试setprority时为了得到一个进程的PID,使用top命令查找到的PID号,后期可以通过自动查找完成

	if (nice(3) == -1)
	{
		perror("nice");
		exit(0);
	}
	
	errno=0;
	nPr = getpriority(PRIO_PROCESS,getpid());
	if (errno  != 0)
	{
		perror("getpriority");
		exit(0);
	}
	
	printf("priority is %d\n",nPr);

	puts("now I will change the priority of firefox process and change nice value to 7");
	errno=0;
	setpriority(PRIO_PROCESS,2076,7);
	printf("now the nice of pid in 5 is %d\n",getpriority(PRIO_PROCESS,firefox));
         //注意这里的firefox必须是pit_t类型,如果直接给出数字,程序的结果是是-1
	
	if (errno !=0)
		perror("getpriority");
	return 0;


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值