Skip to content
systemcoding.dev
Systems Programming

Set Process Priority with nice and setpriority

Lower or raise a process's nice value with nice and setpriority on Linux 6.12 and glibc 2.40, handle the -1 return trap, and know when root is required.

6 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, Rust and FreeBSD logos.

A batch job that compresses logs should not make an interactive shell stutter. The traditional Unix answer is the nice value: a small integer attached to every process that tells the scheduler how willing the process is to yield. Two system calls change it, nice and setpriority, and a third, getpriority, reads it. They look trivial and they have three traps that bite people in their first week: the -1 return value, the privilege rule for going negative, and what "priority" means on a modern Linux scheduler. This post covers all three with complete programs, written for Linux 6.12 and glibc 2.40, with behavior taken from nice(2), setpriority(2) and sched(7).

What the nice value is

The nice value ranges from -20 (most favorable to the process) to 19 (least favorable). The default for a normal process is 0, and a child inherits its parent's value at fork. The name is literal: a high value means the process is being nice to everyone else.

The nice value is not a scheduling deadline and not a guarantee. It is a weight. In the kernel's scheduler documentation, each step of one nice level changes the CPU share of a task by roughly ten percent relative to its neighbors, so two CPU-bound processes at nice 0 and nice 5 share a core in a ratio well short of "the second one starves". Since Linux 6.6 the default scheduler class uses EEVDF rather than CFS, and the nice value still feeds the weight that class uses. What the scheduler does with the weight is an implementation detail; the interface you program against did not change.

The nice value only matters when processes compete. On an idle machine a nice 19 process runs at full speed.

The two calls

nice(int inc) adds inc to the calling process's nice value and returns the new value. setpriority(int which, id_t who, int prio) sets an absolute value for a process, a process group or a user. Both are declared in headers you already include: <unistd.h> for nice, <sys/resource.h> for setpriority and getpriority.

CallEffectReturns
nice(5)Add 5 to my nice valueNew nice value, or -1 on error
setpriority(PRIO_PROCESS, pid, 10)Set process pid to exactly 100 on success, -1 on error
getpriority(PRIO_PROCESS, pid)Read the valueThe value, or -1 on error

Passing 0 as the who argument means "the calling process" for PRIO_PROCESS, "the caller's process group" for PRIO_PGRP, and "the caller's real user" for PRIO_USER.

The -1 trap

Valid nice values include -1. So when nice or getpriority returns -1, you cannot tell whether that is the answer or an error. The documented technique is to set errno to zero before the call and test it afterward:

nice_demo.cc
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/resource.h>
#include <unistd.h>

static int current_nice(void)
{
    errno = 0;
    int value = getpriority(PRIO_PROCESS, 0);
    if (value == -1 && errno != 0) {
        fprintf(stderr, "getpriority: %s\n", strerror(errno));
        return 0;
    }
    return value;
}

int main(void)
{
    printf("start     nice = %d\n", current_nice());

    errno = 0;
    int after = nice(5);
    if (after == -1 && errno != 0) {
        fprintf(stderr, "nice: %s\n", strerror(errno));
        return 1;
    }
    printf("nice(5)   nice = %d\n", after);

    if (setpriority(PRIO_PROCESS, 0, 12) != 0) {
        fprintf(stderr, "setpriority: %s\n", strerror(errno));
        return 1;
    }
    printf("set to 12 nice = %d\n", current_nice());
    return 0;
}

Started from a normal shell, where the nice value is 0, the output is:

Text
start     nice = 0
nice(5)   nice = 5
set to 12 nice = 12

The glibc wrapper for nice returns the new value, which is why the second line prints 5. The raw system call returns 0 on success, and glibc builds the return value by calling getpriority afterward, so the errno discipline above applies to the wrapper exactly as written.

Going the other way needs privilege

Raising your own nice value (being nicer) is always allowed. Lowering it is not:

raise_priority.cc
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/resource.h>

int main(void)
{
    if (setpriority(PRIO_PROCESS, 0, -5) != 0) {
        fprintf(stderr, "setpriority: %s\n", strerror(errno));
        return 1;
    }
    puts("priority raised");
    return 0;
}
Text
setpriority: Permission denied

The error is EACCES when you try to lower the value of your own process without the right. The rule in setpriority(2) is that you need either the CAP_SYS_NICE capability or a high enough RLIMIT_NICE soft limit. That resource limit is expressed as 20 - nice, so a limit of 25 would allow going down to -5. Systems that grant it do so through /etc/security/limits.conf with a nice entry, which is how a desktop session can let an audio server run at a favorable value without root.

A related rule surprises people: once you have raised your nice value as an unprivileged user, you cannot lower it again, because lowering needs the privilege you do not have. If a parent process starts a worker and the worker raises its own value, the parent cannot undo it by calling setpriority on it later unless the parent has the capability.

Setting another process's priority

PRIO_PROCESS takes a process id, which lets a supervisor demote a child it just started:

spawn_low.cc
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = fork();
    if (pid < 0) {
        perror("fork");
        return 1;
    }
    if (pid == 0) {
        execlp("gzip", "gzip", "-9", "-k", "archive.log", (char *)NULL);
        perror("execlp");
        _exit(127);
    }

    if (setpriority(PRIO_PROCESS, pid, 19) != 0)
        fprintf(stderr, "setpriority(%d): %s\n", (int)pid, strerror(errno));

    int wstatus;
    waitpid(pid, &wstatus, 0);
    return WIFEXITED(wstatus) ? WEXITSTATUS(wstatus) : 1;
}

There is a small race here: the child can run for a moment at nice 0 before the parent demotes it. If that matters, call nice(19) in the child between fork and exec, which closes the window because the value is set before the new program starts and survives exec.

A Linux detail the standard hides

POSIX describes the nice value as a property of the whole process. On Linux it is a property of each thread. The kernel treats the who argument of PRIO_PROCESS as a thread id, and setpriority(PRIO_PROCESS, pid, v) with a process id changes only the main thread. The man page notes that this conflicts with POSIX and that the other threads keep their old value. To change a whole multithreaded process you must call setpriority once per thread id, which you can list from /proc/PID/task.

A second detail is autogrouping. With CONFIG_SCHED_AUTOGROUP, which most desktop distributions enable, the kernel groups processes by session and divides CPU between groups first. In that case a nice value only competes against other processes in the same group. Running a nice 19 compile in one terminal does not necessarily protect a nice 0 browser in another session in the way people expect, because the groups are weighed against each other by the group's own value, which you set through /proc/PID/autogroup. The sched(7) page describes the file.

When nice is the wrong tool

The nice value is a hint to a fair scheduler. If a task has a deadline, such as an audio callback, use a real-time policy instead; the guide to SCHED_FIFO and sched_setscheduler covers that, and no nice value turns a normal task into a real-time one. If the problem is that a job uses too much memory or I/O rather than CPU, nice does nothing, and you want cgroup limits or ionice for disk priority. And if you only need to cap total CPU, cgroup cpu.max expresses "this group gets at most half a core", which a nice value cannot.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.