Команда nice linux пример

Команда nice, или вежливые процессы

Когда на компьютере достаточно процессорного времени на исполнение всех процессов, нет необходимости в выставлении приоритетов. Но когда необходимо параллельно запустить несколько процессов, каждый из которых использует всё доступное процессорное время, может очень пригодиться утилита nice.

Команда nice запускает программу с изменённым приоритетом для планироващика задач. Слово «nice» в английском языке обозначает, в частности, «вежливый». По этимологии этой команды процесс с большим значением nice — более вежлив к другим процессам, позволяя им использовать больше процессорного времени, поскольку он сам имеет меньший приоритет (и, следовательно, большее «значение вежливости» — niceness value).

Наибольший приоритет (и наименьшее значение nice) — −20. 19, либо 20 — наименьший приоритет, но это, с другой стороны, самые вежливые процессы.

Чтобы посмотреть идентификатор и значение nice нужного процесса в системе, можно воспользоваться командой ps axl.

Пример использования команды nice — запуск ресурсоёмкой задачи в фоновом режиме, так, чтобы она выполнялась, но освобождала часть процессорного времени для других процессов, как только оно становятся им нужно. Таким образом можно, скажем, запустить кодирование OGG/MP3 с большим значением nice, чтобы оно происходило в фоновом режиме, используя не всё процессорное время, а то, что не используется другими процессами (с меньшим значением nice — то есть с большим приоритетом).

Чтобы запустить команду с определённым приоритетом, слева нужно добавить «nice -n значение_nice», либо «nice —adjustment значение_nice» (adjustment — настройка, регулировка).

То есть: nice -n значение_nice команда.

Если нужно изменить приоритет уже запущенного процесса, можно воспользоваться командой renice.

renice -n значение_nice id_процесса

Команда renice выводит старый и новый приоритет процесса.

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

Источник

nice и renice. Приоритет выполнения

Фактор «уступчивости» — это число, по которому ядро определяет свою политику в отношении процессов, конкурирующих за право доступа к центральному процессору. Чем выше фактор уступчивости, тем ниже приоритет процесса и наоборот, отсюда и название термина. Низкое или отрицательное значение означает использование высокого приоритета: процесс ведет себя не слишком уступчиво.

Читайте также:  Eclipse sdk for linux

Диапазон допустимых значений фактора уступчивости зависит от используемой системы, и обычно он лежит в пределах от -20 до +19. В некоторых системах используется диапазон такого же размера, но со смещением в область неотрицательных чисел (как правило, от 0 до 39). Диапазоны допустимых значений фактора уступчивости, используемые в наших примерах систем, приведены ниже.

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

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

nice

Синтаксис

Описание

Запускает КОМАНДУ с изменённым значением nice, что влияет на приоритет при планировании. Если КОМАНДА не задана, печатает текущее значение nice. Значения nice лежат в диапазоне от -20 (наибольший приоритет) до 19 (наименьший).

Параметры

Опция Значение
-n, —adjustment=N увеличить nice на целое число N (по умолчанию 10)
—help показать эту справку и выйти
—version показать информацию о версии и выйти

renice

Синтаксис

renice [-n] [-p|--pid] . renice [-n] -g|--pgrp . renice [-n] -u|--user .

Описание

Позволяет изменить приоритет выполняемого процесса.

Параметры

Опция Значение
-g, —pgrp interpret argument as process group ID
-n, —priority указать новое значение показателя nice
-p, —pid изменить приоритет по ID процессов (по умолчанию)
-u, —user изменить приоритет процессов пользователя по его имени или ID
-h, —help показать эту справку и выйти
-V, —version показать информацию о версии и выйти

Приоритеты в различных версиях команд nice и renice

Система Диапазон
Linux -20 — 19
Solaris 0 — 39
HP-UX 0 — 39
AIX -20 — 19

Примеры использования

Источник

5+ nice & renice command examples in Linux [Cheat Sheet]

An instance of a program is called a process. When you run any program, it creates a new process. In a Linux system, multiple processes are running at any given time. Each running process has a priority that indicates how fast the system executes it. Processes with a higher priority are usually completed first than with a lower priority.

In Linux, nice command helps to run a program with modified scheduling priority. You can set the priority of the process before it is started using nice command. But you cannot change the priority of the running process with nice command. Therefore, we have renice command to modify the priority of the running process.

How is nice command different from chrt command?

If you are not aware already, chrt command is another way of manipulating the real-time attributes of a process including priority.

«nice» is an historic utility which was used in the early days of batch computing to be «nice» to other users and give up some CPU time. It’s still in use and useful and applies only to processes which run with the SCHED_OTHER policy on Linux.

«chrt» is a tool to change scheduling policy (SCHED_OTHER, SCHED_FIFO, SCHED_RR) and the priority of a process/task. With chrt you can either start a process with such a policy or modify an already running process/tasks policy. You need to have the permissions to do that.

So the main difference is that «nice» can only operate within the nice levels of the SCHED_OTHER policy while «chrt» can change the policy and the priority of a process/task.

How to check the nice value of running process

The nice value ranges from -20 (highest priority) to +19 (lowest priority).

You can check the nice value of the running process using ps command with -l option.

ubuntu@golinux:~$ ps -l F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 0 S 1000 1608 1598 0 80 0 - 4845 do_wai pts/0 00:00:00 bash 0 R 1000 3337 1608 0 80 0 - 5013 - pts/0 00:00:00 ps

The NI column represents the nice value, whereas the PRI column represents the priority value.

You can also use the top command to view the nice value of processes.

top command to check nice value

Syntax to use nice command

The default nice value for processes created by a user is 0.

The syntax for the nice command is:

nice [OPTION] [COMMAND [ARG]. ]

Different examples to use nice and renice command

1. nice command to set the priority of process

You can use -n or —adjustment option to set the nice value of the process.

$ nice -n nice_value command
$ nice --adjustment=nice_value command

Sample Output:

To set the nice value of top command to 10, you can run the command below. It will execute the top command with a nice value of 10.

set the nice value of top with nice command

You can also set the nice value without -n option using a hyphen.

2. nice command to increase the priority of a process

You can use — argument to increase the priority of any process. You can only set the negative nice if you run the command with root or sudo user.

Sample Output:

Here, we assigned -10 nice value to ps -l command.

nice command to set negative nice value

Or, you can specify a nice value with -n flag.

nice command to set negative value

3. nice command to decrease the priority of a process

We can again use -n argument to decrease the priority of a process by using -n along with the process to start. Alternatively we can use — to decrease the priority.

nice command in Linux

4. renice command to change priority of existing process

You can change the priority of the running process with its process ID. The super-user can alter the priority of any process and set the priority to any value. -p or —pid option is used to specify process ID.

$ sudo renice -n nice_value -p process_id
$ sudo renice -n nice_value --pid process_id

Sample Output:

renice command to change priority of process

5. renice command to change the priority of all processes of a specific group

You can modify the priority of all processes belonging to a specific group using the following command.

$ sudo renice -n nice_value -g group_id
$ sudo renice -n nice_value --pgrp group_id

Sample Output:

ubuntu@golinux:~$ sudo renice -n 5 -g 218 218 (process group ID) old priority -1, new priority 5

6. renice command to change the priority of all programs of a specific user

The below command changes the priority of all processes owned by the specific user.

$ sudo renice nice_value --user |

Sample Output:

ubuntu@golinux:~$ sudo renice -n 10 -u ubuntu 1000 (user ID) old priority -11, new priority 10

Conclusion

The nice and renice commands enable users to change or alter the priority of processes in a Linux system. If you still have any confusion, do let us know in the comment section.

What’s Next

Further Reading

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

Команда nice linux пример

NAME

nice - run a program with modified scheduling priority

SYNOPSIS

nice [OPTION] [COMMAND [ARG]. ]

DESCRIPTION

Run COMMAND with an adjusted niceness, which affects process scheduling. With no COMMAND, print the current niceness. Niceness values range from -20 (most favorable to the process) to 19 (least favorable to the process). Mandatory arguments to long options are mandatory for short options too. -n, --adjustment=N add integer N to the niceness (default 10) --help display this help and exit --version output version information and exit NOTE: your shell may have its own version of nice, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports.

AUTHOR

Written by David MacKenzie.

REPORTING BUGS

Report nice bugs to bug-coreutils@gnu.org GNU coreutils home page: http://www.gnu.org/software/coreutils/> General help using GNU software: http://www.gnu.org/gethelp/> Report nice translation bugs to http://translationproject.org/team/>
Copyright © 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.

SEE ALSO

nice(2), renice(1) The full documentation for nice is maintained as a Texinfo manual. If the info and nice programs are properly installed at your site, the command info coreutils 'nice invocation' should give you access to the complete manual.

© 2019 Canonical Ltd. Ubuntu and Canonical are registered trademarks of Canonical Ltd.

Источник

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