Linux как почистить swap

Включить и выключить 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

Узнать, используется ли 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 .

Источник

How to Clear RAM Memory Cache, Buffer and Swap Space on Linux

Like any other operating system, GNU/Linux has implemented memory management efficiently and even more than that. But if any process is eating away your memory and you want to clear it, Linux provides a way to flush or clear ram cache.

How to Clear Cache in Linux?

Every Linux System has three options to clear cache without interrupting any processes or services.

1. Clear PageCache only.

# sync; echo 1 > /proc/sys/vm/drop_caches

2. Clear dentries and inodes.

# sync; echo 2 > /proc/sys/vm/drop_caches

3. Clear pagecache, dentries, and inodes.

# sync; echo 3 > /proc/sys/vm/drop_caches

Explanation of the above command.

sync will flush the file system buffer. Command Separated by “;” run sequentially. The shell waits for each command to terminate before executing the next command in the sequence. As mentioned in the kernel documentation, writing to drop_cache will clean cache without killing any application/service, command echo is doing the job of writing to file.

If you have to clear the disk cache, the first command is safest in enterprise and production as “. echo 1 > ….” will clear the PageCache only. It is not recommended to use the third option above “. echo 3 >” in production until you know what you are doing, as it will clear pagecache, dentries, and inodes.

Is it a good idea to free Buffer and Cache in Linux that might be used by Linux Kernel?

Free Buffer and Cache in Linux

When you are applying various settings and want to check, if it is actually implemented specially on the I/O-extensive benchmark, then you may need to clear the buffer cache. You can drop cache as explained above without rebooting the System i.e., no downtime required.

Linux is designed in such a way that it looks into the disk cache before looking onto the disk. If it finds the resource in the cache, then the request doesn’t reach the disk. If we clean the cache, the disk cache will be less useful as the OS will look for the resource on the disk.

Читайте также:  Linux current user and group

Moreover, it will also slow the system for a few seconds while the cache is cleaned and every resource required by OS is loaded again in the disk cache.

Now we will be creating a shell script to auto clear RAM cache daily at 2 am via a cron scheduler task. Create a shell script clearcache.sh and add the following lines.

#!/bin/bash # Note, we are using "echo 3", but it is not recommended in production instead use "echo 1" echo "echo 3 > /proc/sys/vm/drop_caches"

Set execute permission on the clearcache.sh file.

Now you may call the script whenever you are required to clear the ram cache.

Now set a cron to clear RAM cache every day at 2 am. Open crontab for editing.

Append the below line, save and exit to run it at 2 am daily.

0 2 * * * /path/to/clearcache.sh

For more details on how to cron a job, you may like to check our article on 11 Cron Scheduling Jobs.

Is it a good idea to auto clear the RAM cache on the production server?

Clear RAM Cache on Linux Production Server?

No! it is not. Think of a situation when you have scheduled the script to clear ram cache every day at 2 am. Every day at 2 am the script is executed and it flushes your RAM cache. One day for whatsoever reason may be more than expected users are online on your website and seeking resources from your server.

At the same time, the scheduled script runs and clears everything in the cache. Now all the users are fetching data from the disk. It will result in a server crash and corrupt the database. So clear ram-cache only when required, and known your footsteps, else you are a Cargo Cult System Administrator.

How to Clear Swap Space in Linux?

If you want to clear Swap space, you may like to run the below command.

Also, you may add the above command to a cron script above, after understanding all the associated risks.

Now we will be combining both above commands into one single command to make a proper script to clear RAM Cache and Swap Space.

# echo 3 > /proc/sys/vm/drop_caches && swapoff -a && swapon -a && printf '\n%s\n' 'Ram-cache and Swap Cleared' OR $ su -c "echo 3 >'/proc/sys/vm/drop_caches' && swapoff -a && swapon -a && printf '\n%s\n' 'Ram-cache and Swap Cleared'" root

After testing both the above commands, we will run the command “free -h” before and after running the script and will check the cache.

That’s all for now, if you liked the article, don’t forget to provide us with your valuable feedback in the comments to let us know, what you think is a good idea to clear ram cache and buffer in production and Enterprise?

Источник

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.

Читайте также:  Команда разархивации файла linux

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.

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.

Читайте также:  Play mac games on linux

[ 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. ]

Источник

How to Clear Swap Memory in Linux

Learn how to clear swap in Linux without losing any important data. Also learn why would you clear the swap manually.

Swap is a virtual memory concept that allows your system to use a portion of your hard drive as the physical memory (RAM). Your system swaps the inactive pages in memory in RAM to this swap space on the hard disk. This way, your system has more free RAM available for other programs.

I have shown you to check RAM in Linux and I have also discussed how to check swap usage on Linux. In this quick tip, I’ll show you how to clear swap memory in Linux.

Clear swap in Linux

But first, why would you want to clear swap at all? There could be various reasons. Some time your system will use a lot of swap even when plenty of RAM is available.

This may or may not be associated with swappiness of your system. Sometimes it happens that the RAM doesn’t swap back the pages from swap space to RAM. In such cases, you’ll have to manually clear the swap.

Before clearing the swap, check that you have enough free RAM available to take all the pages from swap. In other words, you should have more free RAM available than the current swap in use.

You can see the state of RAM and swap using the free command in Linux:

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

Once you are sure that the size of free RAM is bigger than the swap memory in use, you can clear the swap memory by turning it off and on again.

Pun aside, that’s the way to do it. Disable all the swap using this command:

Now turn the swap back on:

That’s it. This simple exercise will clear the swap in your Linux system. I hope you find this little tip helpful. Any questions or suggestions are always welcome.

Источник

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