Open System Services Programmer's Guide

Example 28 Determining and Changing Process Priority using getpriority() and nice()
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
extern int errno;
int getpri(int which, id_t who)
{
int cval;
errno = 0;
cval = getpriority(which, who);
if(errno) {
fprintf(stderr, "getpriority error, args = %d, %d\n", which, who);
exit(1);
}
return(cval);
}
int main(int argc, char *argv[])
{
int prval, pval, retcode;
/*
Read the value of the process priority increment from the command line.
If the value is not provided, print usage message and exit.
If the value is invalid, print error message and exit.
*/
if(argc > 1) {
prval = atoi(argv[1]);
if(abs(prval) > (2*NZERO-1)) {
fprintf(stderr, "Invalid priority increment %s\n", argv[1]);
exit(1);
}
} else {
fprintf(stderr, "Usage: nicegetp value [0 to 150]\n");
exit(1);
}
/* Print current process priority value. */
pval = getpri(PRIO_PROCESS, 0);
printf("Current process priority value = %d\n", pval);
/* Print current process group priority value. */
pval = getpri(PRIO_PGRP, 0);
printf("Current process group priority value = %d\n", pval);
/* Print process priority value associated with this user. */
pval = getpri(PRIO_USER, 0);
printf("Process priority value associated with user = %d\n", pval);
/* Set current process priority value */
errno =0;
pval = nice(prval);
if(errno) {
fprintf(stderr, "Can't change process priority by %d\n", prval);
exit(1);
}
112 Managing Processes