Linux what is var cache

Стандарт на структуру каталогов файловой системы. (Filesystem Hierarchy Standard)

5.5 /var/cache : Данные кэша приложений

5.5.1 Назначение

Файлы, расположенные в /var/cache , могут удаляться либо самим приложением, либо администратором. Приложение должно всегда иметь возможность продолжить работу после удаления этих файлов вручную (например, при нехватке дискового пространства). Никаких других требований на формат данных в каталоге кэша не накладывается.

НАЧАЛО ПОЯСНЕНИЙ
КОНЕЦ ПОЯСНЕНИЙ

5.5.2 Рекомендации

«/var/cache»
fonts
man
www

«Каталоги кэширования»
Локально сгенерированные шрифты (optional)
Локально отформатированные страницы руководства (optional)
Кэш данных для WWW proxy (optional)
Кэшируемые данные пакета

(optional)

Дерево 5.5.2.1

5.5.3 /var/cache/fonts : Локально сгенерированные шрифты (optional)

5.5.3.1 Назначение

Каталог /var/cache/fonts должен использоваться для хранения динамически создаваемых шрифтов. В частности, все шрифты, автоматически генерируемые программой mktexpk , должны размещаться в соответствующим образом названных подкаталогах каталога /var/cache/fonts . [примечание 31]

5.5.3.2 Рекомендации

5.5.4 /var/cache/man : Локально отформатированные страницы руководства (optional)

5.5.4.1 Назначение

Структура каталога /var/cache/man должна соответствовать наличию нескольких отдельных деревьев каталогов для страниц руководства и возможности наличия много-языковой поддержки.

В предположении, что не форматированные страницы руководства расположены в каталогах

/man/ /man , форматированные страницы должны располагаться в каталоге /var/cache/man/ / /cat , где получается из

путем удаления подстроки usr из начала и подстроки share в конце имени каталога. [примечание 32] (Обратите внимание на то, что компонент может отсутствовать.)

Страницы руководства, записанные в /var/cache/man , могут быть перенесены в исходные каталоги структуры man или удалены; подобным же образом отформатированные страницы руководства в каталоге man могут быть удалены, если они не использовались в течение какого-то периода времени.

Если заранее отформатированные страницы руководства поставляются с системой на носителе, допускающем только чтение (например, на CD-ROM), они должны устанавливаться в исходную каталоговую структуру man (то есть в /usr/share/man/cat ). Каталог /var/cache/man зарезервирован как перезаписываемый кэш для отформатированных страниц руководства.

НАЧАЛО ПОЯСНЕНИЙ
КОНЕЦ ПОЯСНЕНИЙ

[31] Настоящий стандарт пока не предусматривает поглощение или замену the TeX Directory Structure (документ, который задает размещение файлов формата TeX и структуру соответствующих каталогов), так что этот документ полезно прочитать. Он размещается по адресу ftp://ctan.tug.org/tex/ .

[32] Например, отформатированный вариант страницы /usr/share/man/man1/ls.1 размещается как /var/cache/man/cat1/ls.1 , а /usr/X11R6/man/ /man3/XtClass.3x — как /var/cache/man/X11R6/ /cat3/XtClass.3x . Previous: /var/account : Протоколы работы процессов (optional)
Next: /var/crash : Дампы памяти при крахе системы (optional)
Up: Оглавление
Translated by troff2html v1.5 on 29 March 2002 by Daniel Quinlan

Источник

Can I delete /var/cache/apt/archives for Ubuntu/Debian Linux?

Command to delete /var/cache/apt/archives in Ubuntu/Debian Linux

All .deb packages are retrieved from the Internet and stored in /var/cache/apt/archives/ directory. Similarly, /var/cache/apt/archives/partial/ directory work as storage area for package files in transit. To see files, run:
cd /var/cache/apt/archives/
ls -l
ls -l | tail -10
Use the du command to estimate file space usage and summarize disk usage of /var/cache/apt/archives/, recursively for directories.
sudo du -ch /var/cache/apt/archives/
Sample outputs:

On my personal system 128M disk spaced used by the folder. In other words, APTs cached files are located in /var/cache/apt/archives/ directory.

Is it safe to remove all files?

Yes. See below how to erase those files.

Do we absolutely necessary to keep all these files?

No. See below how to free up disk space.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

apt-get/apt high level package management utility

Let us see some common examples.

Installing a package

sudo apt install For example, install squid3 package, enter:
sudo apt install squid3
You will see downloaded file in /var/cache/apt/archives/
ls -l /var/cache/apt/archives/squid*

Click to enlarge

Removing a package

To remove a package without removing its confi files, use:
sudo apt remove In order to remove a package and its config files, run:
sudo apt remove —purge In this example, delete the nginx and its configuration files:
sudo apt remove —purge nginx
However, this will not remove any downloaded files from the /var/cache/apt/archives/ directory.

How to clear the APT cache and delete everything from /var/cache/apt/archives/

The clean command clears out the local repository of retrieved package files. It removes everything but the lock file from /var/cache/apt/archives/ and /var/cache/apt/archives/partial/. The syntax is:
sudo apt clean
OR
sudo apt-get clean

Delete all useless files from the APT cache

The syntax is as follows to delete /var/cache/apt/archives/:
sudo apt autoclean
OR
sudo apt-get autoclean
From the apt-get man page:

Like clean, autoclean clears out the local repository of retrieved package files. The difference is that it only removes package files that can no longer be downloaded, and are largely useless. This allows a cache to be maintained over a long period without it growing out of control. The configuration option APT::Clean-Installed will prevent installed packages from being erased if it is set to off.

Verify that files are removed from /var/cache/apt/archives/ safely using the du command:
sudo du -ch /var/cache/apt/archives/

Conclusion

This page explained APT cache and how to use the clean and autoclean apt-get command that clears out the downloaded package files from/var/cache/apt/archives/ folder. In short, use the sudo apt clean and sudo apt autoclean to free up disk space as part of scheduled maintenance on your Debian or Ubuntu Linux server.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Можно ли безопасно удалить / var / cache?

Я исчерпал дисковое пространство и отметил, что у меня большой /var/cache каталог. Могу ли я безопасно удалить это? (используя Arch Linux, BTW).

Нет .

Во-первых, я считаю, что /var/cache/bind/ это каталог по умолчанию, в котором bind9 ожидает сохранения файлов своих зон (по крайней мере, в Debian; я не знаю, если другие дистрибутивы следуют этому примеру)

Для другой, в соответствии с этой документацией , pacman (менеджер пакетов, используемый Arch linux) хранит свой кеш пакетов, /var/cache/pacman/pkg/ и он, скорее всего, не ожидает ничего, кроме самого себя, для изменения содержимого.

Я рекомендую вам внимательно прочитать документацию и решить, подходит ли это время для очистки кэша пакетов.

Извините за (очень) поздний ответ, но я считаю, что важно включить этот бит для дальнейшего использования.

Выделил бит, который отвечает на этот вопрос.

Каталог / var / cache содержит кэшированные файлы, то есть файлы, которые были сгенерированы и могут быть сгенерированы заново в любое время, но их стоит хранить, чтобы сэкономить время их повторного вычисления.

Любое приложение может создать файл или каталог здесь. Предполагается, что файлы, хранящиеся здесь, не являются критическими, поэтому система может удалять содержимое / var / cache либо периодически, либо когда его содержимое становится слишком большим.

Любое приложение должно учитывать, что файл, хранящийся здесь, может исчезнуть в любое время, и быть готовым пересчитать его содержимое (с некоторым временным штрафом).

Так что да, вы можете удалить эти файлы, не ожидая ничего плохого.

Как уже говорили другие , /var/cache/ может использоваться любым приложением для хранения информации, чтобы сэкономить на времени поиска. Однако, по моему опыту, большая часть занимаемого там места занимает менеджер пакетов системы.

pacman сохраняет свои загруженные пакеты /var/cache/pacman/pkg/ и не удаляет старые или неустановленные версии автоматически, поэтому необходимо периодически намеренно очищать эту папку, чтобы предотвратить ее бесконечный рост.

Однако , если место для хранения не является отчаянной проблемой, чтобы сохранить головную боль позже, из-за будущей несовместимости; один из этих инструментов следует использовать: paccache , pkgcacheclean или pacleaner .

Для другой системы:

На основе Redhat (Fedora, CentOS, SL, . )

На основе Debian (Ubuntu, . )

Основанный на SUSE

Этот пост показался мне интересным тем, что я искал удаление из / var / cache в Ubuntu 15.10 для улучшения дискового пространства, вот что я нашел:

/ var / cache / apt файлы кеша удаляются после запуска ‘sudo apt-get clean’, однако структура каталогов остается, что не проблема, если вы ищете улучшения дискового пространства; ‘apt-get clean’ должен запускаться последним, если вы хотите улучшить дисковое пространство с помощью apt-get [auto] remove / [auto] clean и т. д.

Что касается всего остального в каталоге, я не мог согласиться с «Tor Valamo» и его объяснением. Это кеш, система и приложения, которые используют кеш, должны иметь возможность восстанавливать все, что они там создали. У вас просто незначительные потери производительности, так как кэш восстанавливается из приложения в приложение

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

Вы можете сделать это определение самостоятельно, используя lsof .

Запустите, lsof -Pn +D /var/cache/ | awk ‘‘ | sort | uniq чтобы увидеть, какое программное обеспечение в настоящее время имеет какие-либо открытые файлы в этом каталоге. Если что-то выглядит умеренно важным (или вы не знаете, что это такое), не удаляйте его.

Кроме того, в любом случае вы не должны просто выбрасывать каталоги без резервных копий; это даже относится к /tmp . Если файл используется в настоящее время, ваше удаление не будет зарегистрировано до тех пор, пока обработчик не будет закрыт (вы увидите, что он исчез в файловой системе). Более того, удаление может привести lsof к аварийному завершению работы других программ (см. Приведенную выше команду), если ожидаемый файл отсутствует.

По сути, удаляйте только те файлы, которые, как вы знаете , безопасны для удаления и в настоящее время не используются другими работающими программами.

Источник

General Filesystem CachingВ¶

OverviewВ¶

This facility is a general purpose cache for network filesystems, though it could be used for caching other things such as ISO9660 filesystems too.

FS-Cache mediates between cache backends (such as CacheFS) and network filesystems:

Or to look at it another way, FS-Cache is a module that provides a caching facility to a network filesystem such that the cache is transparent to the user:

FS-Cache does not follow the idea of completely loading every netfs file opened in its entirety into a cache before permitting it to be accessed and then serving the pages out of that cache rather than the netfs inode because:

It must be practical to operate without a cache.

The size of any accessible file must not be limited to the size of the cache.

The combined size of all opened files (this includes mapped libraries) must not be limited to the size of the cache.

The user should not be forced to download an entire file just to do a one-off access of a small portion of it (such as might be done with the “file” program).

It instead serves the cache out in PAGE_SIZE chunks as and when requested by the netfs(‘s) using it.

FS-Cache provides the following facilities:

More than one cache can be used at once. Caches can be selected explicitly by use of tags.

Caches can be added / removed at any time.

The netfs is provided with an interface that allows either party to withdraw caching facilities from a file (required for (2)).

The interface to the netfs returns as few errors as possible, preferring rather to let the netfs remain oblivious.

Cookies are used to represent indices, files and other objects to the netfs. The simplest cookie is just a NULL pointer — indicating nothing cached there.

The netfs is allowed to propose — dynamically — any index hierarchy it desires, though it must be aware that the index search function is recursive, stack space is limited, and indices can only be children of indices.

Data I/O is done direct to and from the netfs’s pages. The netfs indicates that page A is at index B of the data-file represented by cookie C, and that it should be read or written. The cache backend may or may not start I/O on that page, but if it does, a netfs callback will be invoked to indicate completion. The I/O may be either synchronous or asynchronous.

Cookies can be “retired” upon release. At this point FS-Cache will mark them as obsolete and the index hierarchy rooted at that point will get recycled.

The netfs provides a “match” function for index searches. In addition to saying whether a match was made or not, this can also specify that an entry should be updated or deleted.

As much as possible is done asynchronously.

FS-Cache maintains a virtual indexing tree in which all indices, files, objects and pages are kept. Bits of this tree may actually reside in one or more caches:

In the example above, you can see two netfs’s being backed: NFS and AFS. These have different index hierarchies:

The NFS primary index contains per-server indices. Each server index is indexed by NFS file handles to get data file objects. Each data file objects can have an array of pages, but may also have further child objects, such as extended attributes and directory entries. Extended attribute objects themselves have page-array contents.

The AFS primary index contains per-cell indices. Each cell index contains per-logical-volume indices. Each of volume index contains up to three indices for the read-write, read-only and backup mirrors of those volumes. Each of these contains vnode data file objects, each of which contains an array of pages.

The very top index is the FS-Cache master index in which individual netfs’s have entries.

Any index object may reside in more than one cache, provided it only has index children. Any index with non-index object children will be assumed to only reside in one cache.

The netfs API to FS-Cache can be found in:

The cache backend API to FS-Cache can be found in:

A description of the internal representations and object state machine can be found in:

Statistical InformationВ¶

If FS-Cache is compiled with the following options enabled:

then it will gather certain statistics and display them through a number of proc files.

/proc/fs/fscache/statsВ¶

This shows counts of a number of events that can happen in FS-Cache:

Источник

Читайте также:  Benq fp71g драйвер windows 10
Оцените статью