I created a process and inside I tried to decrease its nice value:
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
int main()
{
printf("Modified nice value: \t %d\n", nice(-19)); // Output: -1; if I run with sudo the output is 0
return 0;
}
Why the output is -1 or 0 if I use sudo? How can I set a nice value equal to -19?
If I try to increase the nice value, the program works properly.
EDIT: sorry for the above code; the output 0 occurs if I run the following code with sudo:
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
int main()
{
int nice_value;
nice_value = getpriority(PRIO_PROCESS, 0);
printf("Default nice value: \t %d\n", nice_value); // 0
nice_value = nice(12);
printf("Modified nice value: \t %d\n", nice_value); // 12 OK
printf("Modified nice value: \t %d\n", nice(20)); // 19
printf("Modified nice value: \t %d\n", nice(-19)); // 0 (sudo)
return 0;
}
Instead if I run the above code (before the edit) with sudo the output is -19. Why the output is 0 in the latter case (the "edit case")?
If I comment the first three printf, the output is -19.
you get 0 instead of -20 because
nice()
adds the value passed to the nice value for the calling thread, so if your current nice value is 19 and you usenice(-19)
19 - 19 = 0 instead if you use nice(-39) you got a nice value of -20 but off course for set lower nice value you need super user privileges, instead for the first question you get -1 from you call to nice because in case of error (like unprivileged process try to set a lower nice value), it return -1, off course it can return -1 also when you try to set a -1 nice value, therefore to differentiate these two cases test theerrno
variable