Очистка swap в linux

How to clear swap

how do I clear the swap? I know it isn’t something that is needed, but I still want to know how to do it. this is what I’m doing so far:

# to check if there is enough space in ram for the swap contents: free -m 
sudo swapoff -a sudo chmod 600 /var/swap sudo mkswap /var/swap sudo swapon -a 

that works for clearing the swap, but it doesn’t turn on again because it isn’t being used until I reboot.

What turns off swap is swapoff -a . Since you already know that I’m not clear what it is that you’re asking

Are you asking «why does swap not turn on after clearing it? Am I doing it right? I want to clear it then continue using it.»

2 Answers 2

1. Without systemd

You can disable swap with swapoff -a . If swap is being used it is not an instantaneous action (see man swapoff ).

If you have defined swap in /etc/fstab you can use swapon -a to activate all known swap files and partitions. If none is defined there you need to declare the swap space that you want to use, for example swapon /var/swap .

There is no need to recreate it each time you want to use it

2. With systemd

The new method for activating swap is through a systemd service, run at boot. You can see its status, for example,

systemctl status dphys-swapfile # What happened last time it ran systemctl restart dphys-swapfile # Recompute the swapfile space and reactivate it 

In turn, systemd calls the dphys-swapfile command (see man dphys-swapfile ), which computes a reasonably sized swapfile partition and activates it, or deactivates it, as required.

dphys-swapfile swapoff # Stop using the swapfile dphys-swapfile setup # (Re-)compute an optimal swap space as /var/swap dphys-swapfile swapon # Start using the computed swapfile 

In the systemd and dphys-swapfile world, swapspace defaults to the file /var/swap rather than a partition

Источник

How to clear swap memory in Linux

box of old photos

Swap memory is usually a «set it and forget it» type of affair. Most enterprise environments have swap built into the systems, and these memory caches are not manipulated unless there is an apparent lack of memory available or if a server crashes due to the OOM killer (out of memory) error. However, there is a niche situation that can cause an administrator to need to clear the system swap manually. If that is the situation that you find yourself in, you’ve come to the right place. This article is a discussion about this situation and the solution required.

Читайте также:  Archiving files in linux

Feeling swappy?

Occasionally, a system uses a high percentage of swap memory even when there is RAM available for use. The culprit here is the ‘swappiness’ of the system. Yep, you read that right. swappiness. So now that you know the lingo, you’re ready to explore what it means. Swappiness refers to the kernel parameter responsible for how much and how often that the system moves data from RAM to swap memory.

The default value for swappiness is 60; however, you can manually set it anywhere between 0-100. Small values cause little swapping to occur, whereas high values can cause very aggressive swapping. A value of zero causes no swapping at all to occur, so if you want to minimize swapping to its lowest possible value without turning it off, you should set it to at least one.

If you wanted to change up the swappiness of your system, the procedure is very straight-forward. You can check your current swappiness setting by running the following command:

It should look something like this:

output of cat /proc/sys/vm/swapiness

Now, you can see that my system has a swappiness value of 30. To alter the value, you want to use the following:

$ sudo sysctl vm.swappiness=x (where x is the swap value you wish to set)

output of sysctl vm.swappiness=60

To verify the value that you set, simply cat the swappiness file that you looked at earlier to find out the original value. Easy day. Now that you understand the underlying parameters that control the swap behavior on our system, you’re ready to learn how to clear that memory, should the situation arise. For the first time in your terminal life, things are going to be easy here.

Читайте также:  Создание файла через командную строку линукс

[ For more information on swap space, see Managing swap in the modern Linux system. ]

To clear the swap memory on your system, you simply need to cycle off the swap. This moves all data from swap memory back into RAM. It also means that you need to be sure you have the RAM to support this operation. An easy way to do this is to run ‘free -m’ to see what is being used in swap and in RAM. Once you power it off, you can wait an arbitrary amount of time (30 sec or so) to give the operation time to complete, then power the swap back on. This clears the swap memory cache and re-enables it. Here are all of the commands you’ll need!

Check space: # free -m Disable swap: # swapoff -a Wait approx 30 sec (use free -m to see the amount of swap used/available decrease over time) Enable swap: # swapon -a 

Hopefully, this quick tip helps you clear your system swap memory if you ever find yourself in need of just such a fix.

[ Want to try out Red Hat Enterprise Linux? Download it now for free. ]

Источник

Включить и выключить swap в linux

Swap – раздел подкачки в linux. Свап используется операционной системой при недостаточом количестве оперативной памяти. Т.е. вместо записи данных в оперативную память, если она практически вся заполнена, данные помещаются на жёсткий диск (свап-раздел). При этом производительность сервера как правило падает (по крайней мере если жёсткий диск не SSD) по причине того, что работа с оперативной памятью происходит гораздо быстрее записи/считывания с жёсткого диска, на котором и располагается файл подкачки (Swap).

Для выключения swap в linux (Ubuntu) без перезагрузки системы нужно воспользоваться командой:

Дожидаемся выполнения команды swapoff. Затем включаем swap:

Можно комбинировать команды, следующие команды выгрузят всё из свап, а затем снова сделают возможным использование свап, т.е. по сути освободят/очистят swap-раздел:

sudo swapoff -a && sudo swapon -a

Если при выключении swap sudo swapoff -a возникает ошибка: Невозможно выделить память, то проблему можно решить перезагрузкой.

Очистить (освободить) swap в linux

sudo swapoff -a && sudo swapon -a

Читайте также:  Linux bash date format

Узнать, используется ли swap

[root@debian ~]$ free -m total used free shared buffers cached Mem: 1002 910 92 0 110 119 -/+ buffers/cache: 679 323 Swap: 879 34 845

В данном случае используется 34Мб swap из доступных 879Мб.

Также можно посмотреть сколько используется swap используя утилиты top или htop .

Источник

Как очистить память подкачки в Linux

Как очистить память подкачки в Linux

У знайте, как очистить swap в Linux без потери важных данных. Также узнайте, почему вы должны очистить файл подкачки вручную.

Подкачка — это концепция виртуальной памяти, которая позволяет вашей системе использовать часть вашего жесткого диска в качестве физической памяти ( ОЗУ ). Ваша система сбрасывает неактивные страницы в памяти в ОЗУ с эту область подкачки на жестком диске. Таким образом, ваша система имеет больше свободной оперативной памяти, доступной для других программ.

Мы показали вам, чтобы проверить оперативную память в Linux, и также обсудили, как проверить использование подкачки в Linux. В этой статье мы покажем вам, как очистить память подкачки в Linux.

Очистка файла подкачки в Linux

Но сначала, почему вы хотите очистить swap вообще? Там могут быть разные причины. Некоторое время ваша система будет использовать много подкачки, даже если много оперативной памяти доступно.

Это может или не может быть связано с перестановкой вашей системы. Иногда случается, что ОЗУ не очищает страницы из пространства подкачки в ОЗУ. В таких случаях вам придется вручную очистить swap.

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

free -h total used free shared buff/cache available Mem: 7.5G 5.4G 211M 916M 1.9G 953M Swap: 14G 1.7G 13G

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

Если отбросить каламбур, то именно так и надо делать. Выключите подкачку с помощью этой команды:

Теперь включите swap обратно:

Вот и все. Это простое упражнение очистит обмен в вашей системе Linux. Мы надеемся, что вы найдете этот маленький совет полезным. Любые вопросы или предложения всегда приветствуются.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

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