-
Notifications
You must be signed in to change notification settings - Fork 12
Process Priority in Linux
A process is an instance of a program in execution. From the kernel's point of view, processes are entities to which system resources (CPU time, memory, etc.) are allocated.
Let's stick to the 134 book and not go into much details on this topic, for now. :)
The process scheduler is a part of the Linux kernel that performs the switching between the processes. Since computers need to run more processes that their CPUs actually have cores, the OS needs to rapidly switch between the processes on a single core.
Process scheduler can use different scheduling policies, but most of the processes are assigned SCHED_OTHER policy (also called SCHED_NORMAL). With SCHED_NORMAL policy, processes can be given a relative priority, also called the nice value and there are 40 different niceness levels, from -20 to 19. Processes inherit the niceness level from their parent. Higher niceness level indicates less priority, which means that the process will easily give its CPU resources to others.
Only root user can set negative nice values and lower the nice values of the processes. Regular users are only allowed to set positive nice levels and they can only increase them, they cannot lower them.
The process inherits the nice level from its parent. If we start a process from a terminal, it will inherit its niceness, which defaults to 0. To start a process with a different nice level, we use nice
utility.
nice <COMMAND>
will start <COMMAND>
with a nice level of 10.
Nice level can be set to a specific value by using nice -n <NICE-LEVEL> <COMMAND>
.
nice -n 15 <COMMAND>
If we want to change the nice level of a process that's already running, we use renice
utility. In this case, we'll be working with PIDs, which we obtain by running pidof <PROCESS-NAME>
.
In the following example, we'll change the nice level of the docker
process
$ pidof docker
6608
'$ ps aox pid,comm,nice | grep docker'
2557 dockerd -2
6608 docker -1 --> we can see that the nice level is -1
$ renice -n -15 6608
$ ps aox pid,comm,nice | grep docker
2557 dockerd -2
6608 docker -15 --> now the nice level is changed to -15
To see how much of CPU power each process takes, we will run:
ps axo pid,comm,nice,pcpu | grep <PROCESS-NAME>
To terminate process by its PID, we use
kill <PID>
kill -<SIGNAL> <PID>
--> for example: kill -SIGKILL <PID>
, you can find the list of available signals on man 7 signal