总结:

int nice(int inc);

进程调度优先级为,nice的取值范围是0~(2*NZERO)-1

一般头文件会定义:优先级的最大值NZERO;

 如果没有可以通过这个函数得到:sysconf(_SC_NZERO);

不管其他书对nice函数的用法怎么说,下面是我通过实际测试得到的

输入:输入参数inc时,inc会以加的形式,设置优先级如:原理优先级为1,而inc为2,则优先级为3,若inc为-1,则优先级为0

输出:成功设置输出inc的值,错误返回-1

下面的程序概述:

1.创建一个子进程,打印父进程和子进程优先级,

2.子进程通过nice函数设置进程优先级

3.最后,两给进程运行10秒,在这10秒中,由于优先级的不同,两个进程分配的时间不同,则cout值就不同,优先级越大,cout的值越大

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#define bufsize 20
unsigned long long count;
struct timeval end;
void
checktime(char *str)
{
struct timeval tv;
gettimeofday(&tv, NULL);
if (tv.tv_sec >= end.tv_sec && tv.tv_usec >= end.tv_usec)
{
printf("%s count = %lld\n", str, count);
exit(0);
}
}
int
main(int argc, char *argv[])
{
pid_t pid;
char *s;
int nzero, ret;
int adj = 0;
int errno = -1;
setbuf(stdout, NULL);
#if defined(NZERO)
nzero = NZERO;
#elif defined(_SC_NZERO)
nzero = sysconf(_SC_NZERO);
#else
#error NZERO undefined
#endif
printf("NZERO = %d\n", nzero);
if (argc == 2)
adj = strtol(argv[1], NULL, 10);
gettimeofday(&end, NULL);
end.tv_sec += 10; /* run for 10 seconds */
if ((pid = fork()) < 0)
{
perror("fork failed");
} else if (pid == 0)
{ /* child */
s = "child";
printf("current nice value in child is %d, adjusting by %d\n",nice(0)+nzero, adj);
errno = 0;
if ((ret = nice(adj)) == -1 && errno != 0)
perror("child set scheduling priority");
printf("now child nice value is %d\n", ret+nzero);
printf("current nice value in child is %d, adjusting by %d\n",nice(0)+nzero, adj);
} else
{ /* parent */
s = "parent";
printf("current nice value in parent is %d\n", nice(0)+nzero);
}
for(;;)
{
if (++count == 0)
printf("%s counter wrap", s);
checktime(s);
}
}

结果:

linux进程调度之nice函数_#include

linux进程调度之nice函数_子进程_02