What is RLIMIT_NICE?
RLIMIT_NICE is a Linux-specific limit (since kernel 2.6.12) that sets a ceiling on the nice value a process can set for itself using nice() or sched_setscheduler(). A lower nice value means higher CPU priority. RLIMIT_NICE prevents unprivileged processes from boosting their own priority above an allowed ceiling.
The Ceiling Formula
Nice values on Linux range from -20 (highest priority) to +19 (lowest priority). The RLIMIT_NICE ceiling is calculated using this formula:
Where rlim_cur is the soft RLIMIT_NICE limit. This means:
Code Example — RLIMIT_NICE
#include
#include
#include
#include
#include <sys/resource.h>
int main(void)
{
struct rlimit rl;
/* Show current RLIMIT_NICE */
getrlimit(RLIMIT_NICE, &rl);
printf("RLIMIT_NICE: soft=%lld hard=%lld\n",
(long long)rl.rlim_cur, (long long)rl.rlim_max);
/* With rlim_cur=0, the ceiling nice value is 20 - 0 = 20
Since nice max is 19, the process can only set nice to +19 or higher
i.e. it cannot raise its priority at all */
/* Set RLIMIT_NICE to 25: ceiling = 20 - 25 = -5
Process can now set nice values down to -5 */
rl.rlim_cur = 25;
rl.rlim_max = 25;
setrlimit(RLIMIT_NICE, &rl);
printf("Set RLIMIT_NICE=25, ceiling nice = %d\n", 20 - 25);
/* Try to set nice to -5 (should now be allowed) */
if (setpriority(PRIO_PROCESS, 0, -5) == -1) {
if (errno == EPERM)
printf("setpriority(-5) denied: EPERM\n");
else
perror("setpriority");
} else {
printf("nice set to -5 successfully\n");
}
/* Try to set nice to -6 (one below ceiling — should fail) */
if (setpriority(PRIO_PROCESS, 0, -6) == -1) {
if (errno == EPERM)
printf("setpriority(-6) denied: EPERM (above ceiling)\n");
}
return 0;
}
/* Compile: gcc -o rlimit_nice rlimit_nice.c */
Interview Questions
ceiling = 20 − rlim_cur. A process can set its nice value to the ceiling or higher (less priority), but not lower (more priority) than the ceiling.
With rlim_cur=0, the ceiling is 20−0=20. Since the maximum allowed nice value is 19, this means the process can use nice values 19 down to 19 (only the lowest priority). It cannot raise its priority at all.
Since Linux kernel 2.6.12. It is Linux-specific and not in SUSv3.
