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.

Читайте также:  Hasp 1с linux x64

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
Total number of priorities = 140 Real time priority range(PR or PRI): 0 to 99 User space priority range: 100 to 139

Nice value range (NI): -20 to 19

PR = 20 + NI PR = 20 + (-20 to + 19) PR = 20 + -20 to 20 + 19 PR = 0 to 39 which is same as 100 to 139.

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.

$ nice -n niceness-value [command args] OR $ nice -niceness-value [command args] #it’s confusing for negative values OR $ nice --adjustment=niceness-value [command args]
  • 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.

$ sudo nice -n 5 tar -czf backup.tar.gz ./Documents/* OR $ sudo nice --adjustment=5 tar -czf backup.tar.gz ./Documents/*

You can also use the third method which is a little confusing especially for negative niceness values.

$ sudo nice -5 tar -czf backup.tar.gz ./Documents/*

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:

$ renice -n -12 -p 1055 $ renice -n -2 -u apache

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,

PR for ts3server = 20 + -12 = 8 PR for apache processes = 20 + -2 = 18

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.

Читайте также:  Reset all user password linux

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:

# vi /etc/security/limits.d/tecmint-priority.conf

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.

Источник

Установка приоритетов для процессов в Linux

Все процессы в системе трудятся с определёнными приоритетами, также называемыми «значениями nice», которые могут изменяться от -20 (верхний приоритет) до 19 (наименьший приоритет). Если оно не определено, каждый процесс будет запускаться с ценностью по умолчанию — 0 («базовым» приоритетом (понятие, показывающее важность, первенство) распределения машинного времени). Для процессов с более рослым приоритетом (меньшим значением nice, вплоть до -20) будет выделено больше целых ресурсов по сравнению с другими процессами с меньшим приоритетом (до 19), предоставляя им большее количество циклов процессора. Все пользователи, кроме рута, могут только понижать приоритет собственных собственных процессов в диапазоне от 0 до 19. Суперпользователь (root) для любого процесса может водворить любое значение приоритета.

Если один или несколько процессов используют очень много ресурсов системы, вы можете изменить их приоритеты вместо того, чтобы уничтожать их. Для этого используется команда renice. Ее синтаксис:

renice приоритет [[-p] pid . ] [[-g] pgrp . ] [[-u] user . ]

Где приоритет — значение приоритета, pid — идентификатор процесса (используйте опцию -p для указания нескольких действий), pgrp — идентификатор группы процесса (если их несколько, используйте -g) и user — имя пользователя, обладающего процессом (-u для нескольких пользователей). Давайте представим, что вы запустили процесс с PID 785, который исполняет длительные научные вычисления, а пока он работает, вы хотели бы немного расслабится и поиграть, для что вам нужно освободить немного системных ресурсов. Тогда вы можете набрать:

В данном случае выполнение вашего процесса потенциально может занять больше времени, хотя он не будет забирать процессорное время у других процессов. Если вы системный администратор и приметили, что какой-то пользователь запустил слишком много процессов, и они используют слишком много целых ресурсов, вы можете изменить приоритет процессов этого пользователя при помощи одной бригады:

После все процессы пользователя peter получат наименьший ценность и не будут затруднять работу процессов других пользователей.

Теперь, когда вы видите о том, что можно изменять приоритеты процессов, вам может понадобиться запустить программу с определенным ценностью. Для этого используйте команду nice. В этом случае вам необходимо указать свою бригаду в качестве опции для nice. Опция -n используется для установки значения приоритета. По умолчанию nice ставит приоритет 10. Например, вам нужно создать ISO-образ установочного CD-ROM’а с Mandrakelinux:

Читайте также:  Linux узнать uid disk

В отдельных системах со стандартным IDE CD-ROM процесс копирования больших объёмов информации может завладеть слишком много ресурсов системы. Чтобы предотвратить блокирование других процессов благодаря копирования, вы можете запустить процесс с пониженным приоритетом при помощи этой команды:

$ nice -n 19 dd if=/dev/cdrom of=~/mdk1.iso

и возобновлять заниматься своими делами.

Источник

Как задать или изменить приоритет процесса в Linux?

Как задать или изменить приоритет процесса в Linux?

В некоторых ситуациях может возникнуть необходимость запускать скрипт/программу не со стандартным приоритетом, а с более высоким или низким, либо повысить или понизить приоритет у запущенного ранее процесса. В данной статье мы рассмотрим несколько способов, как можно это с делать.

Что такое приоритет процесса?

Приоритет процесса определяет, как часто именно этот процесс, по сравнению с другими запущенными процессами, стоящими в очереди на выполнение, будет исполняться процессором. В ОС Linux значение приоритета процесса варьируется в диапазоне значений от -20 до 19 (т.е. получается 40 возможных значений: -20, -19, -18 . 0, 1, 2 . 19) и называется niceness (сокращенно NI). Чем меньше это значение, тем выше приоритет будет у такого процесса. Например, если у нас есть один процесс, работающий с приоритетом 10, а другой процесс работающий с приоритетом 15, то в первую очередь будет выполняться процесс приоритетом 10, а уже после него, тот, где приоритет 15. А в ситуации, когда есть 2 процесса и у одного из них приоритет будет равен -20, а у другого равен 10, то в первую очередь процессор будет обрабатывать тот процесс, у которого приоритет равен -20, а уже после тот, у которого приоритет равен 10.

Как узнать приоритет процесса?

С помощью команды top (все запущенные процессы)

Посмотреть приоритет процесса можно с помощью команды top

С помощью команды ps (конкретный процесс(ы) по его имени)

ps -o pid,comm,nice -C mysqld PID COMMAND NI 706 mysqld 0

С помощью команды ps (конкретный процесс по его PID)

ps -o pid,comm,nice 706 PID COMMAND NI 706 mysqld 0

Задание приоритета при запуске процесса

Для того, чтобы задать приоритет при старте нового процесса, необходимо воспользоваться командой nice
nice -n [значение приоритета] [команда]
Запустить утилиту top с приоритетом 15:

Изменение приоритета у существующего процесса

Для того, чтобы изменить приоритет у существующего процесса (т.е. такого процесса, который ранее был уже запущен), необходимо воспользоваться командой renice
renice [значение приоритета] -p [id процесса]

При понижении приоритета у процесса, который является вашим (т.е. запущен под той же учетной записью, под которой вы работаете в системе) — права суперпользователя не требуются, НО при повышении приоритета у процесса, требуется запускать команду renice с правами суперпользователя, т.е. с помощью sudo renice.
В противном случае, вы будете получать ошибку примерно такого содержания:

sudo renice 0 -p 15483 15483 (process ID) old priority 15, new priority 0

Мы изменили приоритет у существующего процесса (команда top из предыдущего примера) с 15 на 0.

Источник

Оцените статью
Adblock
detector