Set tmp dir linux

12.3.3. Использование переменной окружения TMPDIR

12.3.3. Использование переменной окружения TMPDIR

Многие стандартные утилиты обращают внимание на переменную окружения TMPDIR, используя обозначенный в ней каталог в качестве места для помещения временных файлов. Если TMPDIR не установлена, каталогом по умолчанию для временных файлов обычно является /tmp, хотя на многих современных системах есть также и каталог /var/tmp. /tmp обычно очищается от всех файлов и каталогов административными сценариями оболочки при запуске.

Многие системы GNU/Linux предоставляют каталог /dev/shm, использующий файловую систему типа tmpfs:

$ df

Filesystem 1K-blocks Used Available Use% Mounted on

/dev/hda2 6198436 5136020 747544 88% /

/dev/hda5 61431520 27720248 30590648 48% /d

none 256616 0 256616 0% /dev/shm

Тип файловой системы tmpfs предоставляет электронный (RAM) диск: часть памяти, которая используется, как если бы она была диском. Более того, файловая система tmpfs использует механизмы виртуальной памяти ядра Linux для его увеличения сверх фиксированного размера. Если на вашей системе уйма оперативной памяти, этот подход может обеспечить заметное ускорение. Чтобы протестировать производительность, мы начали с файла /usr/share/dict/linux.words, который является отсортированным списком правильно написанных слов, по одному в строке. Затем мы перемешали этот файл, так что он больше не был сортированным, и создали больший файл, содержащий 500 копий спутанной версии файла:

$ ls -l /tmp/randwords.big /* Показать размер */

-rw-r—r— 1 arnold devel 204652500 Sep 18 16:02 /tmp/randwords.big

$ wc -l /tmp/randwords.big /* Сколько слов? */

22713500 /tmp/randwords.big /* Свыше 22 миллионов! */

Затем мы отсортировали файл, используя сначала каталог /tmp, а затем с TMPDIR, установленным в /dev/shm[125]:

$ time sort /tmp/randwords.big > /dev/null

/* Использование реальных файлов */

$ time TMPDIR=/dev/shm sort /tmp/randwords.big > /dev/null

/* Использование электронного диска */

Интересно, использование электронного диска было лишь незначительно быстрее, чем использование обычных файлов. (В некоторых дальнейших тестах оно было даже в действительности медленнее!) Мы предполагаем, что в игру вступил буферный кэш ядра (см. раздел 4.6.2 «Создание файлов с помощью creat()»), весьма эффективно ускоряя файловый ввод/вывод[126].

У электронного диска есть важный недостаток: он ограничен сконфигурированным для вашей системы размером пространства для подкачки.[127] Когда мы попытались отсортировать файл, содержащий 1000 копий файла с перемешанными словами, место на электронном диске закончилось, тогда как обычный sort завершился благополучно.

Использовать TMPDIR для своих программ просто. Мы предлагаем следующую схему.

const char template[] = «myprog.XXXXXX»;

char *tmpdir, *tfile;

if ((tmpdir = getenv(«TMPDIR»)) == NULL)

/* Использовать значение TMPDIR, если имеется */

tmpdir = «/tmp»; /* В противном случае, /tmp по умолчанию */

count = strlen(tmpdir) + strlen(template) + 2;

/* Вычислить размер имени файла */

tfile = (char *)malloc(count); /* Выделить для него память */

if (tfile == NULL) /* Проверка ошибок */

sprintf(tfile, «%s/%s», tmpdir, template);

/* Создать завершающий шаблон */

fd = mkstemp(tfile); /* Создать и открыть файл */

/* . использование tempfile через fd. */

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

Читайте также

12.1. Организация рабочего окружения

12.1. Организация рабочего окружения Для успешной работы в какой-либо области важно иметь под рукой необходимые инструменты, и будет лучше, если они будут удобными. В работе по созданию сценариев также необходимо хоть немного, но организовать свое рабочее место. В этом

Блоки и строки окружения

Блоки и строки окружения Схема, представленная на рис. 6.1, включает блок окружения процесса. Блок окружения (environment block) процесса содержит последовательность строк вида:Имя = ЗначениеКаждая строка окружения (environment string), будучи символьной строкой, заканчивается нулевым

22.3.3. Переменные окружения

22.3.3. Переменные окружения В программах, работающих с возможностями setuid или setgid, нужно проявлять особую осторожность с установками окружения. Эти переменные определяются пользователем, активизировавшим программу, тем самым открывается путь для атак. Самая явная атака

Читайте также:  Как ограничить частоту процессора windows 10

Переменные окружения

Переменные окружения Переменные окружения в PHPНепосредственно перед запуском сценария сервер передает ему некие переменные окружения с информацией. В определенных переменных содержаться некоторые заголовки, но не все (получить все заголовки нельзя). Далее я приведу

8.8. Настройка окружения пользователя

8.8. Настройка окружения пользователя Как вы уже знаете, при входе любого пользователя в систему для него запускается особый экземпляр оболочки — login shell. В процессе запуска в качестве login shell bash ищет следующие файлы: • /etc/profile •

/.profile (в указанном порядке)

Использование переменной окружения ISC_PATH

Использование переменной окружения ISC_PATH В Yaffil расширены возможности использования переменной окружения ISC_PATH для задания префикса к пути базы данных. Переменная ISC_PATH используется, если в имени базы данных, указываемом клиентом, не содержит каталогов или имени сервера.

10.4. Переменные окружения

10.4. Переменные окружения Когда запускается какая-либо Unix-программа, доступная ей среда включает в себя набор связей «имя-значение» (как имена, так и значения являются строками). Некоторые из них устанавливаются пользователем вручную, другие — системой во время

10.4.1. Системные переменные окружения

10.4.1. Системные переменные окружения Существует множество широко известных переменных окружения, значения которых программа может получить при запуске из оболочки Unix. Данные переменные (особенно НОМЕ) часто требуется оценить до считывания локального файла

10.4.2. Пользовательские переменные окружения

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

10.4. Переменные окружения

10.4. Переменные окружения Когда запускается какая-либо Unix-программа, доступная ей среда включает в себя набор связей «имя-значение» (как имена, так и значения являются строками). Некоторые из них устанавливаются пользователем вручную, другие — системой во время

10.4.2. Пользовательские переменные окружения

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

14.4. Переменные окружения

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

Переменные окружения

Переменные окружения Переменные окружения — глобальные установки системы, которые используются при первоначальной загрузке операционной системы. В Windows, Linux и в большинстве систем UNIX сервер Firebird распознает и использует некоторые переменные окружения, если они

Где устанавливаются переменные окружения

Где устанавливаются переменные окружения WindowsТип переменных окружения и способ их установки меняется от одной версии Windows к другой. В табл. 3.1 показаны типы (если применимы) и способы установки значений переменным окружения.Таблица 3.1. Установки переменных окружения для

СЕЛО ЩЕПЕТНЕВКА: Из окружения

СЕЛО ЩЕПЕТНЕВКА: Из окружения Живу я в центре города. Или почти в центре, как считать. С Главным Памятником Вождю разделяет меня получас неспешной ходьбы, с почтамтом — десять минут, с вокзалом — пять, а с диваном в своей квартире ни секунды не разделяет.Но в этом центре

Источник

Portage TMPDIR on tmpfs

When emerging packages it is possible to build them in tmpfs (RAM) space instead of having build files pushed and pulled to Hard Disk Drive (HDD) or Solid State Drive (SSD) space. Building packages in tmpfs both speeds up emerge times and reduces HDD/SSD wear.

For systems running on a SSD, it is generally a good idea to have Portage compile using tmpfs (RAM) instead burning up (precious) SSD write cycles (especially on something like compiling software).

Generally speaking, unless the system has a large amount of RAM, it may be more of a hassle to setup Portage in tmpfs. Larger packages such as sys-devel/gcc (see below) will fail on only 2 GBs of tmpfs. Keep this in mind when proceeding!

Contents

Configuration

Considering tmpfs’ size

The system’s tmpfs space should be large enough to handle the largest packages to be compiled on the system. If the tmpfs space were to ever become completely full then the emerge will fail. Most packages would not need more than 1 GB for compilation, but there are a few that are very large and would need more. Those still wanting to compile these packages on tmpfs should verify enough free tmpfs space exists. The following list are estimates on how much space would be allocated on each package. Some of these are based on the minimum space requirements specified on the ebuilds themselves. Note that the actual allocated size may vary depending on the features included when building the package. It should also vary on every version update.

Читайте также:  Восстановить скрытые разделы windows 10

An example of a size check failure:

Package Memory usage (uncompressed)
www-client/chromium 10 GBs or so with 3 GBs of extra system memory.
dev-java/icedtea 8.5 GBs
www-client/firefox Around 4.5 GBs; or 13 GBs if the pgo , debug , or test USE flag has been enabled.
dev-lang/rust Around 7 GBs; or 10 GBs if FLAGS has -ggdb set.
sys-devel/gcc More than 4 GBs (will fail with = 8.0.19-r1)
dev-qt/qtwebengine Builds a fork of chromium in the background => 10 GBs or so with 3 GBs of extra system memory.

When using ccache to assist in resuming compiles, it should be noted an equal size of the /var/tmp and /var/tmp/portage directories is necessary. Alternatively the per-package choices as shown below for large packages requiring large amounts of space can be implemented.

ccache creates a directory in /var/tmp/ccache to store compiled elements for resuming. This is why if /var/tmp is a tmpfs it must be of size similar to that of /var/tmp/portage if a amount of system RAM is to be used in this way.

fstab

Mount Portage’s TMPDIR to tmpfs by adding the following to the system’s /etc/fstab config file:

Adjust the size parameter /etc/fstab to the desired amount of RAM. Systems with large amounts of RAM can increase the number quite significantly.

After /etc/fstab has been modified, mount Portage’s TMPDIR to RAM by running the mount command followed by the directory location outline in fstab :

In the unlikely event that the entire /var/tmp/ directory is already mounted as tmpfs, it can be worked around by the special x-mount.mkdir mount option:

Per-package choices at compile time

Portage can be configured to build large packages outside of the tmpfs space on a per-package basis.

Create a file to tell Portage where to place the temporary files directory:

Create a separate temporary file directory outside of the tmpfs mount location:

Create a special Portage file called package.env in /etc/portage/ and list all the packages that are too large to be compiled using tmpfs:

Resizing tmpfs

To resize the current tmpfs instance in /var/tmp/portage , run:

Where N is in the form of bytes. It can also be suffixed with k , m , or g to respectively have the form of (k)ilobytes, (m)egabytes or (g)igabytes. It can also be suffixed with a % to limit the tmpfs instance to the percentage of current physical RAM, the default being 50% when the parameter is not specified.

The resized tmpfs will not persist to the next boot unless the size parameter is modified in /etc/fstab . This is not necessary since a larger tmpfs is only needed during large package compilations.

It is recommended to leave-out at least 1 GB of space for the system to prevent out-of-memory problems. Using swap-disks for some heavy compile-time and link-time instances which are unexpected may also be helpful. Now even if swap-disks are used, reads and writes to it would only be minimal compared to having a physical filesystem behind /var/tmp/portage .

Here is a note about the size parameter in Linux kernel’s documentation which can be found in /usr/src/linux/Documentation/filesystems/tmpfs.txt as long as a kernel has been emerged:

Besides the obvious danger of choking the system by allocating too much memory for tmpfs space, it should be generally safe to enlarge the tmpfs during an emerge as this would only increase the size limit of the tmpfs without destroying any data from the emerge process.

For example, if a system has 12 GB of RAM and 3 disks with 2 GB of swap space working in parallel on each disk, then it would be pretty safe to choose size limit equal to 16G . 16 GB size is usually enough to compile Libreoffice and Chromium in parallel (usual emerge -1uDN @world ) while reading Internet in a web browser.

It’s not often that you’ll ever have to do it and emerge would tell you that tmpfs is too small however there are instances that the package’s ebuild would be not accurate at estimating the amount of disk space necessary for building the package. Newer packages may end up allocating more space, whereas using lesser USE flags would make it allocate less.

The solution for this is to either enlarge tmpfs, or add the exception to /etc/portage/package.env , and then run emerge again.

Save an emerge and resume later

Example: emerging webkit-gtk can take a long time. I want to reboot into another OS and resume this ebuild later.

Optional: I use app-portage/genlop to inspect the current emerge session. I like using it to remind me of the ebuild version number or hopefully to get an estimated time remaining.

Press Ctrl + c to quit the current emerge session.

Since I am rebooting, I’ll have to use cp -a or tar -cpf to save /var/tmp/portage/* while preserving permissions. Otherwise the tmpfs contents will be lost; You may want to inspect the memory size of /var/tmp/portage by using du :

Reboot, do other stuff, come back later.

Resume the ebuild with ebuild / /

If you’re using other repository sources besides gentoo like layman overlays, make sure that you’re using the correct repository directory of the ebuild as one package can also belong to other repositories and be chosen to be installed over the one in gentoo . You can get the repository name of the current package by reading the last action entry in /var/log/emerge.log or reading the build.log file in the package’s build directory with a command like:

Do not use the .ebuild file found in /var/tmp/portage/ /

— .ebuild as it seems to be only a reference. Perhaps there’s a way to use it, but one would have to thoroughly understand how ebuild and ebuild.sh work.

Troubleshooting

No space left on device

If you encounter a not-enough space error or anything similar, there are basically two things to do:

  1. Check the /var/tmp/portage directory for old package directories from previously failed compiles. Any packages found therein should be deleted; with exceptions made for any failed packages the user would like to resume compiling later.
  2. Resize the tmpfs.
  3. In case you still get messages related to exhausted disk space during emerge, even though the allocated tmpfs size is not nearly exceeded (check with du -h during emerge), you may have stumbled upon an inodes shortage. So far it definitely may be a problem for the www-client/chromium package, for it’s grand storage requirements, but can be expected for other large packages as well. To workaround — append nr_inodes=0 to the list of your options for the tmpfs mount in the /etc/fstab file. For additional information refer to ‘tmpfs’ section in man mount .

As last instance, add a (temporary) swap file somewhere on your system with enough capacity:

This will create the file /swap.img with 8GB filled with zeroes.

Set up the swap area using:

Enable the file for swapping:

Check, if the swap file is active:

Compile the packages which would deadlock the computer because of high RAM usage (e.g. chromium):

Alternatively, disable and remove the swap file when finished:

Источник

Читайте также:  Разметка диска mbr для windows 10
Оцените статью