- Где временный каталог в Linux?
- / tmp: временные файлы
- / var / tmp: временные файлы сохраняются между перезагрузками системы
- Where is the temporary directory in Linux?
- 5 Answers 5
- /tmp : Temporary files
- /var/tmp : Temporary files preserved between system reboots
- Linux tmp Directory: Everything You Need to Know
- What is the Linux /tmp Directory?
- What is the difference between the /tmp directory and the /var/tmp Directory?
- Can the Linux /tmp directory fill up?
- How to delete the files stored inside the /tmp directory?
- The correct way to delete Temporary Files and Manage the Linux /tmp directory
- I accidentally deleted the /tmp directory. Now what?
- Wrapping Up
Где временный каталог в Linux?
Есть ли в Linux стандартный временный каталог для общего пользования, например, C:\Temp папка Windows ? Если да, где он находится? Я нашел SO вопрос о программном поиске tmp каталога , но я хочу заранее установить временное местоположение в XML-файле конфигурации.
/ tmp: временные файлы
/tmp Каталог должен быть доступен для программ , которые требуют временных файлов.
Программы не должны предполагать, что какие-либо файлы или каталоги в /tmp них сохраняются между вызовами программы.
обоснование
Стандарт IEEE POSIX.1-2008 перечисляет требования, аналогичные приведенному выше разделу. Хотя данные, хранящиеся в, /tmp могут быть удалены в зависимости от сайта, рекомендуется, чтобы файлы и каталоги, расположенные в /tmp них, удалялись при каждой загрузке системы.
FHS добавил эту рекомендацию на основе исторического прецедента и общепринятой практики, но не сделал ее обязательным требованием, поскольку системное администрирование не входит в сферу применения этого стандарта.
/ var / tmp: временные файлы сохраняются между перезагрузками системы
/var/tmp Каталог доступен для программ , которым требуется временные файлы или каталоги , которые должны сохраняться между перезагрузками системы. Поэтому данные, хранящиеся в, /var/tmp являются более постоянными, чем данные в /tmp .
Файлы и каталоги, расположенные в, /var/tmp не должны быть удалены при загрузке системы. Несмотря на то, что данные, хранящиеся в, /var/tmp как правило, удаляются в зависимости от сайта, рекомендуется, чтобы удаление происходило с меньшей частотой, чем /tmp .
TMPDIR Эта переменная должна представлять путь к каталогу, доступному для программ, которым требуется место для создания временных файлов.
Это старый вопрос, поэтому сегодня есть еще один вариант. Дистрибутивы Linux, на systemd которые полагается (а это 90%), теперь могут использовать $XDG_RUNTIME_DIR каталог ( спецификация XDG Base Directory ) для хранения определенных типов временных файлов. Обычно он находится по адресу /run/user/$uid . Это каталог для пользователя с 700 разрешениями, которые обеспечивают лучшую безопасность. Это tmpfs крепление, которое обеспечивает производительность. Недостатком tmpfs является то, что он должен использоваться только для хранения небольших файлов и сокетов.
Я смотрю на это как на брак /tmp и /var/run .
Да / TMP для общего пользования. Смотрите здесь и здесь О стандарте иерархии файловой системы.
/ tmp / Временные файлы (см. также / var / tmp). Часто не сохраняется между перезагрузками системы.
С некоторыми подробностями, перечисленными в PDF.
Вы не можете заранее выбрать одно временное имя каталога, которое будет работать для любой системы Linux. На самом деле, вы не можете сделать это и в Windows. Согласно статье Википедии о временных папках , временный каталог в Windows определяется переменной среды TEMP. Если бы вы просто использовали c:\Temp в качестве временного каталога в системе Windows, в котором для TEMP установлено другое значение, любая программа, использующая ваш XML-файл для выбора временного каталога, потерпит неудачу.
Короче говоря, системный временный каталог определяется средой во всех известных мне современных операционных системах, включая как Windows, так и любую UNIX-подобную систему. Установка одного статического пути в качестве временного каталога будет работать только до тех пор, пока значения по умолчанию не будут изменены.
Во всяком случае, стандартный временный каталог в типичной системе Linux есть /tmp . Это эквивалент C:\Temp в том смысле, что это только временный каталог по умолчанию, а не универсальный. Даже если /tmp доступно, если пользователь (или система) установил переменную среды TEMP, вместо нее следует использовать значение этой переменной.
Вы можете попробовать выбрать временный каталог относительно домашнего каталога пользователя, который вы можете создать.
Источник
Where is the temporary directory in Linux?
Does Linux have a standard temporary directory for general use, like Windows’s C:\Temp folder? If so, where is it located? I found an SO question about finding a tmp directory programmatically, but I want to set a temp location in an XML config file ahead of time.
5 Answers 5
/tmp : Temporary files
The /tmp directory must be made available for programs that require temporary files.
Programs must not assume that any files or directories in /tmp are preserved between invocations of the program.
Rationale
IEEE standard POSIX.1-2008 lists requirements similar to the above section. Although data stored in /tmp may be deleted in a site-specific manner, it is recommended that files and directories located in /tmp be deleted whenever the system is booted.
FHS added this recommendation on the basis of historical precedent and common practice, but did not make it a requirement because system administration is not within the scope of this standard.
/var/tmp : Temporary files preserved between system reboots
The /var/tmp directory is made available for programs that require temporary files or directories that are preserved between system reboots. Therefore, data stored in /var/tmp is more persistent than data in /tmp .
Files and directories located in /var/tmp must not be deleted when the system is booted. Although data stored in /var/tmp is typically deleted in a site-specific manner, it is recommended that deletions occur at a less frequent interval than /tmp .
TMPDIR This variable shall represent a pathname of a directory made available for programs that need a place to create temporary files.
This is an old question so today there is another option available. Linux distributions relying on systemd (which is 90% of them) can now use $XDG_RUNTIME_DIR directory (XDG Base Directory Specification) to store certain types of temporary files. It is generally located at /run/user/$uid . This is a per-user directory with 700 permissions which provides better security. This is a tmpfs mount which provides performance. The downside of tmpfs is that it should only be used to keep small files and sockets.
I look at it as a marriage of /tmp and /var/run .
Yes /tmp is for general use. See here and here On the Filesystem Hierarchy Standard.
/tmp/ Temporary files (see also /var/tmp). Often not preserved between system reboots.
With some more details listed in the PDF.
You cannot choose a single temporary directory name ahead of time that will work for any Linux system. In fact, you can’t do that on Windows either. According to Wikipedia’s article on temporary folders, the temporary directory on Windows is determined by the environment variable TEMP. If you were simply using c:\Temp as a temporary directory on a Windows system that set TEMP to something else, then any program using your XML file to choose a temporary directory would fail.
In short, the system temporary directory is determined by the environment on all modern operating systems that I know of, including both Windows and any UNIX-like system. Setting a single static path as your temporary directory will only work as long as the defaults have not been changed.
Anyway, the standard temporary directory in a typical Linux system is /tmp . It is the equivalent of C:\Temp in the sense that it is only the default temporary directory, not universal. Even if /tmp is available, if a user (or the system) has set the TEMP environment variable, the value of that variable should be used instead.
You could try choosing a temporary directory relative to the user’s home directory, which you can create.
Источник
Linux tmp Directory: Everything You Need to Know
If you are coming from the Windows environment, the chances are that you may think the tmp directory is something safe to delete. That’s not the case! Unless you know what you are doing, we don’t want advice to remove anything in the tmp directory. Here is everything you need to know. Read on.
A re you looking to expand your knowledge base on how temporary files are handled in Linux? Well, to help you out, here is a quick and comprehensive read on everything you need to know about the Linux /tmp directory.
What is the Linux /tmp Directory?
The /tmp directory in Linux based systems contains necessary files that are temporarily required by the system as well as other software and applications running on the machine.
tmp directory on Pop!_OS (example)
For example, when you are writing a document, all the content inside that document is saved as a temporary file inside the /tmp directory. After you have saved it, it gets stored in your preferred location, and the temporary file gets removed once you exit the document.
What is the difference between the /tmp directory and the /var/tmp Directory?
Both /tmp and /var/tmp are used by programs as well as the system itself to store data temporarily. However, the key difference is for how long the data is stored inside these filesystems. The data retention period for /var/tmp is much more extended than that of the /tmp directory.
By default, all the files and data that gets stored in /var/tmp live for up to 30 days. Whereas in /tmp, the data gets automatically deleted after ten days.
Furthermore, any temporary files that are stored in the /tmp directory get removed immediately on system reboot. As such, the /var/tmp directory is used by programs to store data that needs to be preserved between reboots temporarily.
Can the Linux /tmp directory fill up?
The files and data that are stored inside the /tmp directory are only a few KB in size. It is doubtful, albeit possible, for the /tmp directory to fill up.
For an average system, there needs to be millions of temporary files stored in the /tmp directory to fill it up. This shouldn’t be something you should worry about if you run a single-user system that gets frequently shut down, as the rebooting system removes all the stored files in the /tmp directory.
However, if you are a system admin running a server that rarely gets rebooted and hosts thousands of users, then the /tmp directory filling up is a practical problem.
With more temporary files piling up in the directory, it is going to slowly eat up all the storage space, which is terrible news for the overall system health.
How to delete the files stored inside the /tmp directory?
Unless you know what you are doing, it isn’t recommended that you go around deleting the files inside the /tmp directory. These are important and required by the software running on your system. Removing them can potentially cause a system crash. Since the files and data stored in the /tmp directory get automatically deleted upon system reboot, it isn’t something you need to worry about actively.
However, as discussed earlier, for servers that run for months on end, it is necessary to clean up the temporary files from time to time before it floods the /tmp directory. To do this, we encourage you to take a more systematic approach instead of just deleting all the /tmp files by the bunch.
Here we have put together a detailed read on how to properly manage the Linux /tmp directory to help out system admins.
The correct way to delete Temporary Files and Manage the Linux /tmp directory
There are two things you need to consider when trying to manage the Linux /tmp directory. First, you need to know how to determine which files to remove from the /tmp directory, as randomly deleting the files will disrupt users’ activities.
Secondly, you need a way to automate the /tmp directory clean up process as it is going to be impossible to search and routinely delete the temporary files manually.
Considering these two points, the perfect solution would be periodically deploying user file housekeeping scripts using crontab. For example, let’s suppose that you want to routinely delete all user files stored in the /tmp directory that has not been used for the last three days.
Well, you can put this to action by first informing the users on your server about your new temporary file deletion policy, so that they can modify their usage activities accordingly. Next, you will need to write a script that will help you find all these files.
Here is an example that you can try:
The above script will find all the /tmp files that haven’t been accessed in the last three days but will exclude all the files owned by the root user. To delete all these files, you will just to do a slight edit to the above script:
To run this script periodically, you will need to copy the above text in a file and make it executable. For this tutorial, we will be creating the file tmp.cleanup.sh.
Script for deleting /tmp files
Next, we will set up a crontab command that will execute the script every 6 hours. To do this, first enter the following command in the terminal:
This is going to open the crontab file in the editor. Next, you will need to copy and paste the given command in the editor and then save & exit.
Creating a /tmp file deletion crontab
This is going to run the script in /opt/scripts/tmp.cleanup.sh, every 6 hours, so you don’t have to worry about the /tmp directory getting flooded and eating up your system storage.
Of course, you are free to program the crontab to execute the script in any periodic interval you want. Here is an in-depth guide on how to create a crontab command to help you out.
I accidentally deleted the /tmp directory. Now what?
In the course of manually deleting the /tmp files, some users accidentally end up deleting the /tmp directory itself. Mess ups like this can and do happen. However, you can quickly restore the deleted /tmp directory using the discussed method.
All you need to do is enter the following commands in your terminal:
The first line creates a new /tmp directory. The second line gives all users (owner, group, and other) access and permission to read, write, and run files in the /tmp directory.
Next, you can enter this command to check all the permissions of the /tmp directory to make sure all your users will be able to use it.
Once you have checked everything is a-okay, you will need to reboot your system. This will ensure that the programs start using the newly created /tmp directory.
Wrapping Up
So that covers everything you need to know about the Linux /tmp directory. However, if you still have some burning questions that we left out from this read, then feel free to ask them down in the comments section. We will happily resolve it to help you develop a better understanding and appreciation for Linux.
Источник