Linux: make your processes act nice

The nice command allows to schedule the execution priority of processes. In other words controls how much CPU time will assigned to a…

Linux: make your processes act nice
Photo by Sven on Unsplash

The nice command allows to schedule the execution priority of processes. In other words controls how much CPU time will assigned to a process relative to other processes, this ensures that important processes get the CPU time is necessary to operate smoothly, Lets see how this works with some examples.

Syntax

The basic syntax for the nice command is

nice -n <value> <program> <program args>

the -n parameter can take values ranging from -20 (highest priority) to 19 (lowest priority)

The default “niceness” for a process not started with nice is 0, the default “niceness” starting a program with nice but not using the -n parameter is 10 which is a lowest priority than 0.

Examples

How to start a process with the default niceness

Enter the following to start a process with default niceness of nice , this will start myprogram with niceness 10.

nice myprogram

How to start a process with lowest priority

Enter the following to start a process with the lowest niceness (19), this will start myprogram with niceness 19.

nice -n 19 myprogram

How to start a process with highest priority

Enter the following to start a process with the highest niceness (-20), this will start myprogram with niceness -20

nice -n -20 myprogram

How to check the niceness of a running process

We can check the niceness of a running process using the ps command with the following formating options

ps -o pid,nice,cmd -p <PID>

This is an example output for PID 1709 in my system.

ps -o pid,nice,cmd -p 1709                                                                                                                  20:33:47 
  PID NI 
 1709  0

How to change the niceness of a running process

To change the niceness of a running process we use the renice command, the following command will set niceness to 2 for process with PID 1234.

renice 2 -p 1234

Conclusion

nice and renice are essential commands for any system admunor devops engineer. Those commands give you the power (and responsibility) to change how a process will consume CPU time, use it carefully ;)