Linux top swap usage

Как быстро выяснить какой процесс в Linux использует пространство подкачки (swap)

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

Исходные данные: ОС Oracle Linux 7;
Задач: Найти потребителя SWAP

Типичная ситуация на сервере с системой мониторинга — это аларм вида:
prod-srv-01 Low free swap space (free: 0.15 %, threshold: 10%, alert started: 8.79 %)

Вначале немного теории, о том как получить информацию о распределении памяти процессами в Linux.

  • /proc/meminfo — псевдо-файл который сообщает статистику об использовании памяти в системе. Вы также можете использовать утилиты free, vmstat и другие инструменты, чтобы узнать ту же информацию;
  • /proc/$/smaps, /proc/$/status и /proc/$/stat — используйте эти псевдо-файлы для поиска информации о потреблении памяти каждым процессом ($ замените на номер процесса);
  • smem — утилита (скрипт python), которая поможет вывести информацию в более удобном виде;

    Теперь идем на сервер и смотрим:

    Мы видим, что swap заполнен на 100% — это плохо.

    Попробуем быстро выяснить кто основной потребитель, для этого обратимся к /proc/*/status
    Ниже простой сценарий на bash который выдаст нам список потребителей swap:

    Результат будет длинным, я покажу только TOP потребителей:

    Мы видим, что основной потребитель — это процесс ora_j001_bs. На сервере установлен Oracle и один из процессов потребляет swap.
    На втором месте мы видим процесс rsyslogd — думаю он в представлении не нуждается.

    Если на потребителя №1 мы не можем повлиять быстро, то на потребителя №2 (rsyslogd) можем — это попытаться его перазапустить.

    Выполняем перезапуск rsyslogd:

    И смотрим состояние swap:

    Мы видим, что стало доступно 1.6 GB, а это уже более 30% от размера swap, что вполне нас должно устроить на первое время.

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

    Источник

    linux-notes.org

    Утилиты top/htop и free отображают общее количество свободной, занятой физической памяти, а так же SWAP на сервере. Как определить, какой процесс использует пространство подкачки в Unix/Linux?

    Вы можете использовать любой из следующих методов (но имейте в виду, что из-за общих страниц, нет никакого надежного способа получить данную информацию):

    • Используйте «/proc/meminfo» – Утилита, которая покажет общие сведения об RAM/SWAP. Данная статистика используется с утилитой «free», чтобы сообщить количество свободной и используемой памяти (как физической, так и swap) в системе, а также общей памяти и буферов используемых ядром. Вы также можете использовать free, vmstat и другие инструменты чтобы узнать ту же информацию.
    • «/proc/$/smaps», «/proc/$/status» и «/proc/$/stat» — Используя эти утилиты, чтобы найти информацию о памяти, страницах и swap-е используемых каждым процессом( зная PID процесса).
    • Используя smem.

    Какие процессы заняли SWAP в Unix/Linux

    Можно добиться желаемого результата несколькими способами.

    Находим идентификатор процесса (PID):

    Альтернатива, использовать «pgrep» команду для поиска PID-а:

    И так, одна из команд выведет подобный результат:

    Чтобы увидеть сколько использует swap служба memcached можно следующим образом:

    И так, я показал сколько используется swap-а по указанному процессу ( memcached), но это не совсем удобно т.к имеется и ряд других процессов которые могут или использует swap, по этому — я сейчас покажу как можно красиво использовать данные утилиты для проверки.

    Введите следующую команду в терменале, чтобы увидеть использование свопа по каждому процессу:

    Небольшая оптимизация — используем сортировку и вывод частями:

    Нашел небольшой bash скрипт:

    И прописываем в него:

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

    Данные скрипт покажет все процессы которые используют или не используют SWAP, но можно убрать ненужно ( отображать только те процессы, которые имеют обращение к свапу):

    Выход будет в килобайтах.

    Вот уже готовый, упрощенный скрипт:

    Хочу показать отличную вариацию данного скрипта ( на мой взгляд — одно из самых лучших):

    Вот еще один вариант использования:

    Они все работают и их можно использовать для своих нужд. А можно использовать утилиту smem. О ней можно прочитать тут:

    А на этом, у меня все! Статья «Какие процессы заняли SWAP в Unix/Linux» завершена.

    Источник

    8 Useful Commands to Monitor Swap Space Usage in Linux

    Memory management is an essential aspect of every System Administrator to improve the performance of a Linux system. It is always a good practice to monitor swap space usage in Linux to ensure that your system operates relative to its memory demands.

    8 Commands to Check Linux Swap Space Usage

    Therefore in this article we are going to look at ways to monitor swap space usage in a Linux systems.

    What is Swap space?

    Swap space is a restricted amount of physical memory that is allocated for use by the operating system when available memory has been fully utilized. It is memory management that involves swapping sections of memory to and from physical storage.

    On most distributions of Linux, it is recommended that you set swap space when installing the operating system. The amount of swap space you can set for your Linux system may depend on the architecture and kernel version.

    How do I check Swap space usage in Linux?

    We shall look at different commands and tools that can help you to monitor your swap space usage in your Linux systems as follows:

    1. Using the swapon Command

    This command helps you to specify the devices on which paging and swapping will be done and we shall look at few important options.

    To view all devices marked as swap in the /etc/fstab file you can use the —all option. Though devices that are already working as swap space are skipped.

    If you want to view a summary of swap space usage by device, use the —summary option as follows.

    Use —help option to view help information or open the manpage for more usage options.

    2. Using /proc/swaps which is equivalent to swapon

    The /proc filesystem is a very special virtual filesystem in Linux. It is also referred to as a process information pseudo-file system.

    It actually does not contain ‘real’ files but runtime system information, for example system memory, devices mounted, hardware configuration and many more. Therefore you can also refer to it as a control and information base for the kernel.

    To understand more about this filesystem read our article: Understanding /proc File System in Linux.

    To check swap usage information, you can view the /proc/swaps file using the cat utility.

    3. Using ‘free’ Command

    The free command is used to display the amount of free and used system memory. Using the free command with -h option, which displays output in a human readable format.

    From the output above, you can see that the last line provides information about the system swap space. For more usage and examples of free command can be found at: 10 free Command to Check Memory Usage in Linux.

    4. Using top Command

    The top command displays processor activity of your Linux system, tasks managed by kernel in real-time. To understand how the top command works, read this article: 12 top Commands to Check Linux Process Activity

    To check swap space usage with the help of ‘top’ command run the following command.

    Check Swap Space Using Top Command

    5. Using atop Command

    The atop command is a system monitor that reports about activities of various processes. But importantly it also shows information about free and used memory space.

    Atop Check Swap Usage

    To know more about how to install and use atop command in Linux, read this article: Monitor Logging Activity of Linux System Processes

    6. Using htop Command

    The htop command is used to view processes in an interactive mode and also displays information about memory usage.

    Htop Check Swap Usage

    For more information regarding installation and usage about htop command, read this article: Htop – Interactive Linux Process Monitoring

    7. Using the Glances Command

    This is a cross-platform system monitoring tool that displays information about running processes, cpu load, storage space usage, memory usage, swap space usage and many more.

    Glances Check Swap Usage

    For more information regarding installation and usage about glances command, read this article: Glances – An Advanced Real Time Linux System Monitoring Tool

    8. Using the vmstat Command

    This command is used to display information about virtual memory statistics. To install vmstat on your Linux system, you can read the article below and see more usage examples:

    VmStat Check Swap Usage

    You need to take note of the following in the swap field from the output of this command.

    1. si: Amount of memory swapped in from disk (s).
    2. so: Amount of memory swapped to disk (s).

    Summary

    These are easy methods one can use and follow to monitor swap space usage and hope this article was helpful. In case you need help or want to add any information relating to memory management in Linux systems, please post a comment. Stay connected to Tecmint.

    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.

    Источник

    How to Check Swap Usage Live via the ‘top’ Command in Linux

    Question: How to view the system-wide swap usage on a CentOS/RHEL server via the top command to identify the highest consumers.

    Below are the steps for CentOS/RHEL 5 and 6 which are the same, followed by CentOS/RHEL 7 as they differ on this release:

    For CentOS/RHEL 5 and 6

    1. Run the TOP command:

    2. On your keyboard press the “f” key followed by “p” to add the Swap column, Hit enter.

    3. Next, upper case “O” and finally “p” sort by swap, Hit enter.

    4. Perform your review as needed and press “q” to exit top command.

    For CentOS/RHEL 7

    1. Run the TOP command:

    2. On your keyboard press the “f” key and scroll down using the [down] arrow key until you have selected “SWAP” then press [Space] to select it. This should add a “*” symbol in front of it.

    3. While still selecting “SWAP” press the [right] arrow key, which highlights the entire SWAP line, and using the [top] arrow key move it up to one of the first options (anywhere above “COMMAND”).

    4. While still having “SWAP” selected, type the “s” key which will configure top to SORT by the currently selected option, in this case, SWAP. You will not see any changes on the screen when you press “s”, but the setting is saved in the backend.

    5. Finally “q” to save the configuration changes and view the results.

    6. Perform your review as needed and press “q” again to exit top command.

    For more information on top options and fields review the man page. Below are a few lines from the top man page that provide some information on the memory fields and what they represent.

    Источник

    How to Check Swap Space in Linux

    Check swap memory in Linux

    You can check swap the same way you check memory usage in Linux: using the free command.

    If you use the free command with human readable output (with option -h), it will show you the RAM and Swap uses.

    For my system, it shows the following output:

    As you can see in the above output, my system has 14 GB of total swap space and out of that 1.1 GB is being used. Around 13 GB of swap space is free.

    There are more ways to check swap usage in Linux and you may get some additional information about swap as well.

    Other ways to check swap usage in Linux

    My favorite way to check swap usage in Linux is by using the swapon command. This is a command dedicated for handling swap memory. Apart from giving accurate information about the swap space being used, it also tells you if the swap space is a partition or a swap file.

    You can use it like this:

    As you can see in the output, the total swap space is 14.9 GB (not 14 GB as free command showed). 1.1 GB is being used and it’s a swap partition, not a swap file.

    Using swap file is a better idea because you easily increase swap size on Linux with it. Changing swap partition is not a good idea.

    Another way to get swap memory details is by using the /proc/meminfo file. The proc directory in Linux filesystem hierarchy stores system usage information for running processes.

    Here’s the output:

    You can also check swap usage in Linux with top, htop or any other system monitoring tool.

    Bonus Tip: Find out which process is using swap space in Linux

    You can use an open source utility smem to get more accurate memory usage in Linux. smem is not installed by default so you will have to install it using your distribution’s package manager.

    In Ubuntu, smem is available in the universe repository. You can install it using this command:

    Once installed, you can use smem to check which process is using how much swap on your system.

    You can simply use smem command in the terminal but if your focus is to check swap usage, I suggest reverse sorting it on swap in the following manner:

    It will show all the running process in reverse order of swap utilization:

    The memory utilization is in kb.

    Well, I hope you now know how to check swap memory usage in Linux. You may also want to learn about clearing swap on Linux.

    If you are using swap file, you can learn to increase swap size in this video on our YouTube channel:

    If you have questions or suggestions, please let me know in the comments below.

    Источник

    Читайте также:  Docker on windows tutorial
  • Оцените статью