734 Chapter 35
Under the round-robin time-sharing algorithm, processes can’t exercise direct control
over when and for how long they will be able to use the CPU. By default, each process
in turn receives use of the CPU until its time slice runs out or it voluntarily gives up the
CPU (for example, by putting itself to sleep or performing a disk read). If all processes
attempt to use the CPU as much as possible (i.e., no process ever sleeps or blocks on an
I/O operation), then they will receive a roughly equal share of the CPU.
However, one process attribute, the nice value, allows a process to indirectly
influence the kernel’s scheduling algorithm. Each process has a nice value in the
range –20 (high priority) to +19 (low priority); the default is 0 (refer to Figure 35-1).
In traditional UNIX implementations, only privileged processes can assign themselves
(or other processes) a negative (high) priority. (We’ll explain some Linux differ-
ences in Section 35.3.2.) Unprivileged processes can only lower their priority, by
assuming a nice value greater than the default of 0. By doing this, they are being
“nice” to other processes, and this fact gives the attribute its name.
The nice value is inherited by a child created via fork() and preserved across
an exec().
Rather than returning the actual nice value, the getpriority() system call service
routine returns a number in the range 1 (low priority) to 40 (high priority), calcu-
lated according to the formula unice = 20 – knice. This is done to avoid having a
negative return value from a system call service routine, which is used to indicate
an error. (See the description of system call service routines in Section 3.1.)
Applications are unaware of the manipulated value returned by the system call
service routine, since the C library getpriority() wrapper function reverses the
calculation, returning the value 20 – unice to the calling program.
Figure 35-1: Range and interpretation of the process nice value
Effect of the nice value
Processes are not scheduled in a strict hierarchy by nice value; rather, the nice
value acts as weighting factor that causes the kernel scheduler to favor processes
with higher priorities. Giving a process a low priority (i.e., high nice value) won’t
cause it to be completely starved of the CPU, but causes it to receive relatively less
CPU time. The extent to which the nice value influences the scheduling of a pro-
cess has varied across Linux kernel versions, as well as across UNIX systems.
Starting in kernel 2.6.23, a new kernel scheduling algorithm means that relative
differences in nice values have a much stronger effect than in previous kernels.
As a result, processes with low nice values receive less CPU than before, and pro-
cesses with high nice values obtain a greater proportion of the CPU.
–20
0
+19
(high priority)
(low priority)
(traditionally) only available
to privileged processes
nice
value
(default)