Finding the current niceness valueBefore we start changing niceness values I want to go over identifying what the current nice values are.
Determining the default niceness value of new processesDifferent OS distributions can have different default values for new processes. The simplest method to determine the default value is to simply run the nice command with no arguments. By default nice will simply return the current niceness value.
$ nice 0
Determining the niceness value of a current processThe niceness value of current processes are also pretty simple to find as they are visible in the ps command's long format.
In the below example we are going to find the current niceness value of the sshd (PID 941) process.
$ ps -lp 941 F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 4 S 0 941 1 0 70 -10 - 1713 poll_s ? 00:00:00 sshd
NIis the niceness value of the sshd process. In this case it is currently set to
Making a process nicer, decreasing the CPU PriorityNiceness values range from -20 (the highest priority, lowest niceness) and 19 (the lowest priority, highest niceness). In order to prevent a process from stealing CPU time from high priority processes, we will increase the processes niceness value.
Changing the nice value of a new processChanging the niceness value of a new process is fairly simple. The nice command itself will run the supplied command with the desired niceness value.
$ nice -n 19 ./test.sh My niceness value is 19
Changing the nice value of a running processTo change the niceness value of a running process we will utilize the renice command. The usage is similar to nice however rather than supplying a command to run we will be supplying a process id.
In this example we will be adjusting the priority of the sshd process I showed above.
# renice -n 10 -p 941 941 (process ID) old priority -10, new priority 10
Making a process less nice, increasing CPU priorityNow that we have adjusted processes to becoming nicer to the system, let us make a process that is less nice. By changing the priority of a process to a negative number, we are suggesting to the scheduler that it should provide higher priority to the specified process.
Changing the nice value of a new processThe method of changing a process to be less nice is the same as making a process nicer.
# nice -n -20 ./test.sh My niceness value is -20
Changing the nice value of a running processTo change the niceness of a running process to a negative value we will use the renice command again.
# renice -n -10 -p 941 941 (process ID) old priority 10, new priority -10
It is advisable to reserve setting niceness values to -20 only when absolutely necessary; as this would suggest to the kernel scheduler that the specified process has the same CPU priority as kernel worker threads.