linux下进程优先级编程

来源:互联网 发布:龙卷风软件下载 编辑:程序博客网 时间:2024/05/01 08:54
//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类型,如果直接给出数字,程序的结果是是-1if (errno !=0)perror("getpriority");return 0;}

0 0