- How to Set Linux Process Priority Using nice and renice Commands
- Understanding the Linux Kernel Scheduler
- Understanding Process Priority and Nice Value
- How to Check Nice Value of Linux Processes
- Difference Between PR or PRI and NI
- How to Run A Command with a Given Nice Value in Linux
- Change the Scheduling Priority of a Process in Linux
- How To Set Default Nice Value Of a Specific User’s Processes
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- A brief guide to priority and nice values in the linux ecosystem
- ИТ База знаний
- Полезно
- Навигация
- Серверные решения
- Телефония
- Корпоративные сети
- Приоритеты процессов Linux
How to Set Linux Process Priority Using nice and renice Commands
In this article, we’ll briefly explain the kernel scheduler (also known as the process scheduler), and process priority, which are topics beyond the scope of this guide. Then we will dive into a little bit of Linux process management: see how to run a program or command with modified priority and also change the priority of running Linux processes.
Understanding the Linux Kernel Scheduler
A kernel scheduler is a unit of the kernel that determines the most suitable process out of all runnable processes to execute next; it allocates processor time between the runnable processes on a system. A runnable process is one which is waiting only for CPU time, it’s ready to be executed.
The scheduler forms the core of multitasking in Linux, using a priority-based scheduling algorithm to choose between the runnable processes in the system. It ranks processes based on the most deserving as well as the need for CPU time.
Understanding Process Priority and Nice Value
The kernel stores a great deal of information about processes including process priority which is simply the scheduling priority attached to a process. Processes with a higher priority will be executed before those with a lower priority, while processes with the same priority are scheduled one after the next, repeatedly.
There are a total of 140 priorities and two distinct priority ranges implemented in Linux. The first one is a nice value (niceness) which ranges from -20 (highest priority value) to 19 (lowest priority value) and the default is 0 , this is what we will uncover in this guide. The other is the real-time priority, which ranges from 1 to 99 by default, then 100 to 139 are meant for user-space.
One important characteristic of Linux is dynamic priority-based scheduling, which allows the nice value of processes to be changed (increased or decreased) depending on your needs, as we’ll see later on.
How to Check Nice Value of Linux Processes
To see the nice values of processes, we can use utilities such as ps, top or htop.
To view processes nice value with ps command in user-defined format (here the NI the column shows the niceness of processes).
View Linux Processes Nice Values
Alternatively, you can use top or htop utilities to view Linux processes nice values as shown.
Check Linux Process Nice Values using Top Command
Check Linux Process Nice Values using Htop Command
Difference Between PR or PRI and NI
From the top and htop outputs above, you’ll notice that there is a column called PR and PRI receptively which shows the priority of a process.
This, therefore, means that:
- NI – is the nice value, which is a user-space concept, while
- PR or PRI – is the process’s actual priority, as seen by the Linux kernel.
How To Calculate PR or PRI Values
Nice value range (NI): -20 to 19
But if you see a rt rather than a number as shown in the screenshot below, it basically means the process is running under real-time scheduling priority.
Linux rt Process
How to Run A Command with a Given Nice Value in Linux
Here, we will look at how to prioritize the CPU usage of a program or command. If you have a very CPU-intensive program or task, but you also understand that it might take a long time to complete, you can set it a high or favorable priority using the nice command.
The syntax is as follows:
- If no value is provided, nice sets a priority of 10 by default.
- A command or program run without nice defaults to a priority of zero.
- Only root can run a command or program with increased or high priority.
- Normal users can only run a command or program with low priority.
For example, instead of starting a program or command with the default priority, you can start it with a specific priority using following nice command.
You can also use the third method which is a little confusing especially for negative niceness values.
Change the Scheduling Priority of a Process in Linux
As we mentioned before, Linux allows dynamic priority-based scheduling. Therefore, if a program is already running, you can change its priority with the renice command in this form:
Change Process Priority
From the sample top output below, the niceness of the teamspe+ with PID 1055 is now -12 and for all processes owned by user apache is -2 .
Still using this output, you can see the formula PR = 20 + NI stands,
Watch Processes Nice Values
Any changes you make with renice command to a user’s processes nice values are only applicable until the next reboot. To set permanent default values, read the next section.
How To Set Default Nice Value Of a Specific User’s Processes
You can set the default nice value of a particular user or group in the /etc/security/limits.conf file. Its primary function is to define the resource limits for the users logged in via PAM.
The syntax for defining a limit for a user is as follows (and the possible values of the various columns are explained in the file):
Now use the syntax below where hard – means enforcing hard links and soft means – enforcing the soft limits.
Alternatively, create a file under /etc/security/limits.d/ which overrides settings in the main file above, and these files are read in alphabetical order.
Start by creating the file /etc/security/limits.d/tecmint-priority.conf for user tecmint:
Then add this configuration in it:
Save and close the file. From now on, any process owned by tecmint will have a nice value of 10 and PR of 30.
For more information, read the man pages of nice and renice:
You might also like to read these following articles about Linux process management.
In this article, we briefly explained the kernel scheduler, process priority, looked at how to run a program or command with modified priority and also change the priority of active Linux processes. You can share any thoughts regarding this topic via the feedback form below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
A brief guide to priority and nice values in the linux ecosystem
Apr 16, 2019 · 4 min read
How does Linux do memory management to execute your processes is a little complicated thing to explain. But luckily all the abstracted details around memory management like memory allocation and context switching b/w processes are very well optimized and developers don’t have to worry about these things while writing high-level code.
What we should generally take into consideration is the amount of CPU bandwidth that our processes are eligible for, especially in cases of contention with other processes sharing the processing power of the CPU.
Before we jump i nto the priority and nice values and how they help us; It is important to have a top-level understanding of how CPUs run multiple processes at the same time.
Basically, if a CPU has n cores then it can only execute n processes in parallel.
When the number of processes is more than n, the processes are switched between very fast using advanced context-switching mechanisms to provide multitasking. This lets us run multiple processes on a CPU even if it has just 1 core.
Why worry about the priority of your process?
Some processes may be highly CPU-intensive but not as important as others and hence can have a lower priority while others may or may not be highly CPU-intensive but are very important and hence should have higher priority.
For example- if there is a process A, which detects fraud with input data and there is another process B, which makes hourly backups of some data, then the priority(A) > priority(B)!
This ensures that if both A and B are running at the same time, A would be allocated more processing bandwidth.
Now that we have enough context, let’s dive into the specifics.
Priority value — The priority value is the process’s actual priority which is used by the Linux kernel to schedule a task.
In Linux system priorities are 0 to 139 in which 0 to 99 for real-time and 100 to 139 for users.
Nice value — Nice values are user-space values that we can use to control the priority of a process. The nice value range is -20 to +19 where -20 is highest, 0 default and +19 is lowest.
The relation between nice value and priority is as such —
Priority_value = Nice_value + 20
To see how these work together let us take a process that takes a lot of processing power continuously. I’ll use a shell script (infinite.sh) which has an infinite loop in it to demonstrate how this works.
We’ll run this on a single core CPU for easy understanding & use top command (a program that periodically displays a sorted list of system processes and their details like pid, priority value, nice value, CPU usage, etc.) to monitor processes.
The output for top before running infinite.sh:
Once we run infinite.sh in the background using sh infinite.sh & we see that this process (PID-28) is taking 100% processing power of the CPU.
If I run two more processes of infinite.sh then all of them (PID-28,30,32) get equal CPU as all have the same priority.
Now let us give these processes different nice values.
There are two ways to do this:
1. Start the process with the nice value in the command as
nice -n nice_val [command]
For us, it could be something like nice -n 10 sh infinite.sh &
When we run this we get another process (PID-34) with the priority as 30 (as priority = 20 + nice_value). As it has the least priority, it gets the least amount of CPU.
2. Change the nice value of a running process using its PID using renice as renice -n nice_val -p [pid]
For us, it could be something like renice -n 5 -p 28
When we run this, the process with PID-28 gets its priority set from 20 to 25 and the CPU is allocated accordingly.
Note: Only root user can set the nice value from -20 to 19. Other users can only set nice values from 0 to 19.
You can also use renice to set nice values to all processes by a user using renice -n nice_val -u [user]
Источник
ИТ База знаний
Курс по Asterisk
Полезно
— Узнать IP — адрес компьютера в интернете
— Онлайн генератор устойчивых паролей
— Онлайн калькулятор подсетей
— Калькулятор инсталляции IP — АТС Asterisk
— Руководство администратора FreePBX на русском языке
— Руководство администратора Cisco UCM/CME на русском языке
— Руководство администратора по Linux/Unix
Навигация
Серверные решения
Телефония
FreePBX и Asterisk
Настройка программных телефонов
Корпоративные сети
Протоколы и стандарты
Приоритеты процессов Linux
4 минуты чтения
Данная тема важна так как позволяет изменять приоритет процессов в операционной системе Linux. Иногда возникает такая ситуация, что необходимо изменить приоритет процессов, какой — то процесс сделать более приоритетным, отдав побольше ресурсов, а какой-то менее приоритетным забрав часть ресурсов сервера. В данной теме мы рассмотрим следующие вопросы:
Онлайн курс по Linux
Мы собрали концентрат самых востребованных знаний, которые позволят тебе начать карьеру администратора Linux, расширить текущие знания и сделать уверенный шаг к DevOps
- Научимся определять приоритеты процессов;
- Рассмотрим, как запускать программы с повышенным приоритетом или с пониженным;
- Посмотрим, как изменять приоритет запущенных программы.
В Linux любой процесс может иметь приоритет от -20 до +19. Во FreeBSD до +20. Максимальным приоритетом считается, тот процесс у которого минимальное число. Т.е. максимальный по приоритету процесс будет иметь число — 20, а минимальный -19 соответственно. Поэтому задача с приоритетом -20 будет выполняться в первую очередь с максимум ресурсов и наоборот задача с +19 будет выполняться в последнюю очередь и минимум ресурсов. Linux для установки приоритетов использует такую программу nice и renice.
Для того, чтобы рассмотреть данную тему воспользуемся командой ps aux . Запуская данную команду мы получаем все сведения о запущенных процессах на данном сервере. Так же мы можем увидеть от какого пользователя данный процесс запущен. Теперь мы используем другой набор ключей для команды ps .
Чтоб получить нам интересующий вывод данных используем команду ps alx .
Мы можем видеть, что получили немного другую информацию. Появилась колонка, промаркированная «NI» и колонка «PRI«. Мы можем видеть, что верхние процессы выполняются с nice 0, т.е. это авторитет по умолчанию, который присваивается если не сказано иного. Возьмем другой вариант команды ps , с другими ключами.
- ps -eo user,pid,pcpu,nice,comm
- -e — ключ показывать все
- -o — output т.е какая информация нужна, далее в команде перечисляется необходимая информация (колонки)
После ввода данной команды, мы видим, что столбцов стало меньше. Только то, что мы запрашивали, пользователь, ID процесса, загрузка CPU, приоритет и какая команда.
Для того, чтобы понять, что такое приоритет, попробуем использовать команду sleep, которая позволяет, остановить операционную систему на указанное число секунд.
И выведем команду ps -eo user,pid,pcpu,nice,comm | grep sleep , используя pipline сортируем по названию процесса sleep. Вот, что у нас вышло.
Видим наш запущенный процесс.
Далее запустим какую-нибудь задачу с максимальным приоритетом. Это полезно если мы хотим запустить, какой ни будь серьезный процесс, чтобы он получил максимальный приоритет. Как пример, срочная переиндексация базы данных на сервере с максимальным приоритетом или программку, которая будет собирать информацию о системе с минимальным приоритетом.
И мы можем увидеть, что появился наш процесс со значение 10 по умолчанию.
Десять — это приоритет по умолчанию, и он ниже, чем ноль. Чем выше значение, тем приоритет ниже. Т.е. получается если мы запускаем с командой niсе, то процесс запускает с приоритетом ниже в 2 раза, чем просто если бы запустили.
Мы можем принудительно завершить процессы. killall sleep .
Попробуем запустить задачу с минимальным приоритетом. Для этого воспользуемся параметром. Команда будет выглядеть следующим образом.
Как мы видим все получилось. Процесс запущен с минимальным приоритетом.
Аналогично запускается процесс с максимальным приоритетом.
Тут нужно пояснить, что задачи с наивысшим приоритетом, могут пользователи только с правами root. Если мы бы попытались сделать из-под обычного пользователя, то ничего у нас бы не вышло.
killall sleep , еще раз завершим принудительно процессы. Запустим еще раз процесс с наименьшим приоритетом. nice -n 19 sleep 60000 . Теперь изменим приоритет текущего процесса. Для этого есть следующая команда:
Как мы видим все успешно поменялось. Вот таким образом мы можем динамически менять приоритеты. В Операционной системе Windows мы так же можем менять приоритеты в менеджере задач, но если там пять уровней, то в Linux их получается 40.
Мы можем так же менять приоритеты определенному пользователю.
Данные команды, нам позволяют гибко управлять распределением ресурсов на нашем сервере.
Онлайн курс по Linux
Мы собрали концентрат самых востребованных знаний, которые позволят тебе начать карьеру администратора Linux, расширить текущие знания и сделать уверенный шаг к DevOps
Источник