Hard Limits and Soft limits in Linux
I am trying to understand how these limits work. But I am not able to figure it out, why soft limit is needed in the first place when hard limit is present. Most of the sites I have gone through talk about what they are, but none mentioned about how do they work.
In context of processes, Can anyone explain it how do these work?
1 Answer 1
Let us consider a user abc whose number of processes are set as
When this user logs in, the user has the effective soft limit of processes applied i.e., abc can run a maximum of 1024 processes. When this limit is used up, the user will not be able to run any more processes unless the soft limit is increased further.
At this point, the user can optionally increase (but should not be greater than the hard limit) the process limit.
If the user tries to increase it to 21000 (which is above the hard limit of 20000 )
But setting it to any value lesser or equal to the hard limit is accepted. Increasing hard limit can be done only by root .
Can’t we just use the hard limits?
Setting soft limit equal to hard limit would make the hard limit be the default limit for abc user. But it is not recommended as it could lead to a single user exhausting most of the processes (if the limit set is relatively high) that can be totally spawned ( pid_max ).
Soft limit vs Hard limit?
Can anyone explain in layman’s terms what the difference between soft and hard limit is?
Should I set my soft and hard limit to be the same? Or should soft be significantly lower? Does the system benefit either way?
3 Answers 3
The hard limit is the ceiling for the soft limit. The soft limit is what is actually enforced for a session or process. This allows the administrator (or user) to set the hard limit to the maximum usage they wish to allow. Other users and processes can then use the soft limit to self-limit their resource usage to even lower levels if they so desire.
Users who violate a soft limit quota get an e-mail indicating that they have a few days’ grace period before the penalties kick in. Users who cross the hard limit threshold get no such grace period. The penalty differs depending on the particular quota, but usually nearly every command will fail such that the user will want to come into compliance quickly.
User resource limits dictate the amount of resources that can be used for a particular session. The resources that can be controled are:
It is important to note that these settings are per-session. This means that they are only effective for the time that the user is logged in (and for any processes that they run during that period). They are not global settings. In other words, they are only active for the duration of the session and the settings are not cumulative. For example, if you set the maximum number of processes to 11, the user may only have 11 processes running per session. They are not limited to 11 total processes on the machine as they may initiate another session. Each of the settings are per process settings during the session, with the exception of the maximum number of processes.
There are two types of limits that can be set for each property listed above, a hard and soft limit.
Как увеличить лимит Открытых файлов в Ubuntu/Debian/CentOS/Fedora
Периодически при работе сервера вы можете столкнуться с ошибкой » Too many open files » в Linux системах. Чаще всего это бывает на нагруженных серверах. Это значит, что сервер достиг лимита на количество открытых файлов. Этот лимит может быть указан для конкретного пользователя или сессии.
В этой статье я расскажу какие бывают лимиты (а их два вида) и как их увеличить.
- Жесткий лимит — максимальное количество открытых файлов для пользователя или сессии. Устанавливается только администратором/root
- Мягкий лимит — текущее эффективное значение для пользователя или сессии. Может быть изменен самим пользователем, но значение не может превышать жесткого лимита.
Проверка текущих лимитов
Для контроля лимита ресурсов в Linux имеется утилита ulimit .
Получим текущее значение лимитов:
В результате выполнения команды вы увидите список текущих лимитов, а именно тип лимита и его значение.
Чтобы узнать жесткий и мягкие лимиты, используйте следующие команды:
ulimit -Sn # Мягкий лимит
ulimit -Hn # Жесткий лимит
Увеличение лимита для текущей сесии
Большинство операционных систем позволяют изменить лимит открытых файлов для текущей сессии с помощью команды ulimit -n :
Увеличение лимита для пользователя
Вы также можете изменить лимиты для каждого пользователя в отдельности. Для этого нужно отредактировать файл /etc/security/limits.conf в удобном вам редакторе, в моем случае это будет vim
и добавить в него следующие строки:
* soft nproc 65535
* hard nproc 65535
* soft nofile 65535
* hard nofile 65535
max soft nproc 20000
max hard nproc 20000
max soft nofile 20000
max hard nofile 20000
Это значит, что для пользователя » max » будут установлены лимиты в 20000 , а для всех остальных пользователей — 65535 . Измените эти значение по своему усмотрению.
Изменение лимита для всей системы
Вы также можете изменить лимиты для всех пользователей системы, для этого нужно отредактировать параметры sysctl . Откройте в редакторе файл /etc/sysctl.conf и добавьте следующую строку:
После чего примените эти изменения командой
Этим вы установили лимиты для всей системы. Лимиты для конкретного пользователя или сессии не могут превышать лимитов системы.
Как увеличить количество открытых файлов в Linux
В Linux вы можете изменить лимит открытых файлов. Это можно сделать путем использования команды ulimit. Она дает возможность контролировать ресурсы, доступные для оболочки или запущенного ею процесса.
В этом кратком руководстве мы покажем вам, как проверить текущий лимит открытых файлов и их описание. Для этого вам потребуется получить root-доступ к вашей системе.
Давайте посмотрим, как мы можем узнать лимит открытых файловых дескрипторов в вашей системе Linux.
Как найти количество открытых файлов в Linux
Значение сохраняется в
Номер, который вы увидели, показывает количество файлов, которые пользователь мог открыть для каждого сеанса входа. Результат может отличаться в зависимости от вашей системы.
Например, на сервере CentOS ограничение было установлено на 818354
Если вы хотите увидеть Hard и Soft лимит, используйте следующие команды:
Проверка Hard лимит в Linux
Проверка Soft лимит в Linux
Чтобы просмотреть значения Hard и Soft для разных пользователей, переключите пользователя с «su» на пользователя, ограничения которого вы хотите проверить.Например:
Как проверить количество системных дескрипторов файлов в Linux
На серверах, некоторые из ваших приложений могут потребовать более высокий лимит для открытых дескрипторов файлов. Хорошим примером этого являются службы MySQL / MariaDB или веб-сервер Apache.
Вы можете увеличить лимит открытых файлов в Linux, отредактировав опцию ядра fs.file-max. Для этого используйте утилиту sysctl.
Sysctl используется для настройки параметров ядра.
Например, чтобы увеличить ограничение на количество открых файла до 500000, вы можете использовать следующую команду:
Вы можете проверить текущее значение для количества открытых файлов с помощью следующей команды:
С помощью указанной команды изменения, которые вы внесли, будут оставаться активными только до следующей перезагрузки. Если вы хотите применить их на постоянной основе, вам придется отредактировать следующий файл:
Добавьте следующую команду:
Конечно, вы можете изменить число в соответствии с вашими потребностями. Чтобы снова проверить изменения, используйте:
Чтобы изменения вступили в силу, пользователям необходимо будет выйти из системы и снова войти в систему. Если вы хотите немедленно применить ограничения, вы можете использовать следующую команду:
Установка количества открытых файлов для пользователя в Linux
Вышеприведенные примеры показали, как установить ограничения, но вы можете установить лимит для каждого пользователя. Для этой цели, с правами пользователя root, вам необходимо отредактировать следующий файл:
Если вы администратор Linux, предлагаем Вам ознакомиться с этим файлом. Прочитайте все комментарии в нем, поскольку он обеспечивает гибкость в плане управления системными ресурсами путем установки лимита пользователям на разных уровнях.
Команды, которые вы должны добавить, имеют следующие параметры:
Вот пример установки Soft и Hard лимитов для пользователя dimon:
Спасибо за уделенное время на прочтение статьи!
Если возникли вопросы, задавайте их в комментариях.
Подписывайтесь на обновления нашего блога и оставайтесь в курсе новостей мира инфокоммуникаций!
Soft limit vs hard limit
I ran into a problem of :
I know that nproc is the problem Some suggested to increase the soft limit of nproc while other suggested the hard limit.
Which should I increase? Isn’t the soft limit is there just to warn the user and the hard limit is the one that really limits eventually?
2 Answers 2
It’s actually other way around.
The soft limit’s value(s) is actually implemented i.e. in use, you can increase the limit upto the relevant hard limit’s value(s) (assuming you are not super user or do not have CAP_SYS_RESOURCE capability).
Think of the hard and the soft limits as mandatory and discretionary limits, resp. The hard limit is imposed by the system (through suitable configuration, e.g. limits.conf(5) ) and can be increased only by the superuser (i.e. root), while the user can gauge soft limits at his discretion within the range of the according hard limits.
From the getrlimits(2) manual page:
The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit: an unprivileged process may set only its soft limit to a value in the range from 0 up to the hard limit, and (irreversibly) lower its hard limit.
Thus, if you hit a resource limit, then check whether you can increase the according soft limit; if not, then the hard limit needs to be increased.
Response to Comment
There is no such thing as only the hard limit. Limits are set by setrlimit(2) , which refers to struct rlimit . This in turn has members for soft and hard limit ( rlim_cur and rlim_max , resp.). If a soft limit is not explicitly defined, then it defaults to some value; most likely the according hard limit, but this is up to the process that sets the limits. ( setrlimits(2) rejects rlim_cur exceeding rlim_max , so RLIM_INFINITY is typically not a valid default for rlim_cur .)