Руководство по команде mktemp с примерами для начинающих
Руководство по команде mktemp с примерами
Mktemp является частью пакета GNU coreutils.
Так что не беспокойтесь об установке.
Мы рассмотрим некоторые практические примеры
Чтобы создать новый временный файл, просто запустите:
Вы увидите вывод, как показано ниже:
Как видно из выходных данных, в каталоге / tmp создается новый временный файл со случайным именем «tmp.yjcVSaKkuv».
Этот файл просто пустой файл.
Как насчет временного каталога?
Да, это тоже возможно!
Чтобы создать временный каталог, используйте параметр -d.
Это создаст случайный пустой каталог в папке / tmp.
Все файлы будут созданы с разрешением u + rw, а каталоги – с u + rwx, за вычетом ограничений umask.
Вы можете проверить права доступа к файлу или каталогу с помощью команды ls.
Точно так же, чтобы создать каталог, просто запустите:
Обратите внимание, что если вы выберете произвольное имя, файлы / каталоги будут создаваться в текущем рабочем каталоге, а не в / tmp.
В этом случае вам необходимо вручную очистить их.
Также, как вы могли заметить, X в имени файла заменяются случайными символами
Однако вы можете добавить любой суффикс по вашему выбору.
Теперь у нас есть суффикс «blog» в конце имени файла.
Если вы не хотите создавать какой-либо файл или каталог, вы можете просто выполнить пробный запуск, как показано ниже.
Для получения справки выполните:
Зачем нам на самом деле нужен mktemp?
Вы можете спросить, зачем нам нужен «mktemp», в то время как мы можем легко создавать пустые файлы с помощью команды «touch filename».
Команда mktemp в основном используется для создания временных файлов / каталогов со случайным именем.
Таким образом, нам не нужно выяснять имена.
Так как mktemp рандомизирует имена, столкновения имен не будет.
К роме того, mktemp создает файл / каталог безопасно с разрешением 600, поэтому другие пользователи не могут получить к нему доступ.
Для более подробной информации, обратитесь к справочным страницам.
Источник
Linux create temp file
If you need to use a temporary file in your program, you can use the tmpfile function to open it. Or you can use the tmpnam (better: tmpnam_r ) function to provide a name for a temporary file and then you can open it in the usual way with fopen .
The tempnam function is like tmpnam but lets you choose what directory temporary files will go in, and something about what their file names will look like. Important for multi-threaded programs is that tempnam is reentrant, while tmpnam is not since it returns a pointer to a static buffer.
These facilities are declared in the header file stdio.h .
Function: FILE * tmpfile (void)
Preliminary: | MT-Safe | AS-Unsafe heap lock | AC-Unsafe mem fd lock | See POSIX Safety Concepts.
This function creates a temporary binary file for update mode, as if by calling fopen with mode «wb+» . The file is deleted automatically when it is closed or when the program terminates. (On some other ISO C systems the file may fail to be deleted if the program terminates abnormally).
This function is reentrant.
When the sources are compiled with _FILE_OFFSET_BITS == 64 on a 32-bit system this function is in fact tmpfile64 , i.e., the LFS interface transparently replaces the old interface.
Function: FILE * tmpfile64 (void)
Preliminary: | MT-Safe | AS-Unsafe heap lock | AC-Unsafe mem fd lock | See POSIX Safety Concepts.
This function is similar to tmpfile , but the stream it returns a pointer to was opened using tmpfile64 . Therefore this stream can be used for files larger than 2^31 bytes on 32-bit machines.
Please note that the return type is still FILE * . There is no special FILE type for the LFS interface.
If the sources are compiled with _FILE_OFFSET_BITS == 64 on a 32 bits machine this function is available under the name tmpfile and so transparently replaces the old interface.
Function: char * tmpnam (char * result )
Preliminary: | MT-Unsafe race:tmpnam/!result | AS-Unsafe | AC-Safe | See POSIX Safety Concepts.
This function constructs and returns a valid file name that does not refer to any existing file. If the result argument is a null pointer, the return value is a pointer to an internal static string, which might be modified by subsequent calls and therefore makes this function non-reentrant. Otherwise, the result argument should be a pointer to an array of at least L_tmpnam characters, and the result is written into that array.
It is possible for tmpnam to fail if you call it too many times without removing previously-created files. This is because the limited length of the temporary file names gives room for only a finite number of different names. If tmpnam fails it returns a null pointer.
Warning: Between the time the pathname is constructed and the file is created another process might have created a file with the same name using tmpnam , leading to a possible security hole. The implementation generates names which can hardly be predicted, but when opening the file you should use the O_EXCL flag. Using tmpfile or mkstemp is a safe way to avoid this problem.
Function: char * tmpnam_r (char * result )
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
This function is nearly identical to the tmpnam function, except that if result is a null pointer it returns a null pointer.
This guarantees reentrancy because the non-reentrant situation of tmpnam cannot happen here.
Warning: This function has the same security problems as tmpnam .
Macro: int L_tmpnam
The value of this macro is an integer constant expression that represents the minimum size of a string large enough to hold a file name generated by the tmpnam function.
Macro: int TMP_MAX
The macro TMP_MAX is a lower bound for how many temporary names you can create with tmpnam . You can rely on being able to call tmpnam at least this many times before it might fail saying you have made too many temporary file names.
With the GNU C Library, you can create a very large number of temporary file names. If you actually created the files, you would probably run out of disk space before you ran out of names. Some other systems have a fixed, small limit on the number of temporary files. The limit is never less than 25 .
Function: char * tempnam (const char * dir , const char * prefix )
Preliminary: | MT-Safe env | AS-Unsafe heap | AC-Unsafe mem | See POSIX Safety Concepts.
This function generates a unique temporary file name. If prefix is not a null pointer, up to five characters of this string are used as a prefix for the file name. The return value is a string newly allocated with malloc , so you should release its storage with free when it is no longer needed.
Because the string is dynamically allocated this function is reentrant.
The directory prefix for the temporary file name is determined by testing each of the following in sequence. The directory must exist and be writable.
- The environment variable TMPDIR , if it is defined. For security reasons this only happens if the program is not SUID or SGID enabled.
- The dir argument, if it is not a null pointer.
- The value of the P_tmpdir macro.
- The directory /tmp .
This function is defined for SVID compatibility.
Warning: Between the time the pathname is constructed and the file is created another process might have created a file with the same name using tempnam , leading to a possible security hole. The implementation generates names which can hardly be predicted, but when opening the file you should use the O_EXCL flag. Using tmpfile or mkstemp is a safe way to avoid this problem.
SVID Macro: char * P_tmpdir
This macro is the name of the default directory for temporary files.
Older Unix systems did not have the functions just described. Instead they used mktemp and mkstemp . Both of these functions work by modifying a file name template string you pass. The last six characters of this string must be ‘ XXXXXX ’. These six ‘ X ’s are replaced with six characters which make the whole string a unique file name. Usually the template string is something like ‘ /tmp/ prefix XXXXXX ’, and each program uses a unique prefix .
NB: Because mktemp and mkstemp modify the template string, you must not pass string constants to them. String constants are normally in read-only storage, so your program would crash when mktemp or mkstemp tried to modify the string. These functions are declared in the header file stdlib.h .
Function: char * mktemp (char * template )
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
The mktemp function generates a unique file name by modifying template as described above. If successful, it returns template as modified. If mktemp cannot find a unique file name, it makes template an empty string and returns that. If template does not end with ‘ XXXXXX ’, mktemp returns a null pointer.
Warning: Between the time the pathname is constructed and the file is created another process might have created a file with the same name using mktemp , leading to a possible security hole. The implementation generates names which can hardly be predicted, but when opening the file you should use the O_EXCL flag. Using mkstemp is a safe way to avoid this problem.
Function: int mkstemp (char * template )
Preliminary: | MT-Safe | AS-Safe | AC-Safe fd | See POSIX Safety Concepts.
The mkstemp function generates a unique file name just as mktemp does, but it also opens the file for you with open (see Opening and Closing Files). If successful, it modifies template in place and returns a file descriptor for that file open for reading and writing. If mkstemp cannot create a uniquely-named file, it returns -1 . If template does not end with ‘ XXXXXX ’, mkstemp returns -1 and does not modify template .
The file is opened using mode 0600 . If the file is meant to be used by other users this mode must be changed explicitly.
Unlike mktemp , mkstemp is actually guaranteed to create a unique file that cannot possibly clash with any other program trying to create a temporary file. This is because it works by calling open with the O_EXCL flag, which says you want to create a new file and get an error if the file already exists.
Function: char * mkdtemp (char * template )
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
The mkdtemp function creates a directory with a unique name. If it succeeds, it overwrites template with the name of the directory, and returns template . As with mktemp and mkstemp , template should be a string ending with ‘ XXXXXX ’.
If mkdtemp cannot create an uniquely named directory, it returns NULL and sets errno appropriately. If template does not end with ‘ XXXXXX ’, mkdtemp returns NULL and does not modify template . errno will be set to EINVAL in this case.
The directory is created using mode 0700 .
The directory created by mkdtemp cannot clash with temporary files or directories created by other users. This is because directory creation always works like open with O_EXCL . See Creating Directories.
Источник
BASH Shell: HowTo Create Empty Temporary Files Quickly
U se any one of the following command to create temporary empty file names. The first command is special as it use the redirection operator >, the redirection refers to the standard output. So you are creating a new file or destroying existing file:
The touch command can be also used to create temporary empty file names:
mktemp Command
To make temporary unique filename use the mktemp command. In this example, create temporary filename in using a user’s $TMPDIR environment variable:
- 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 ➔
Use /tmp/tmp.yTfJX35144 to store your output. You can store filename to a variable:
The following bash scripting illustrates a simple use of mktemp where the script should quit if it cannot get a safe temporary file
The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of ‘Xs’ appended to it, for example /tmp/tfile.XXXXXXXXXX.
TMPDIR Environment Variable
By default mktemp will use user’s $TMPDIR. If not defined it will use /tmp. You can use the specified directory as a prefix when generating the temporary filename. The directory will be overridden by the user’s TMPDIR environment variable if it is set. In this example the temporary file will be created in /chroot/apache/var/tmp unless the user’s TMPDIR environment variable specifies otherwise:
Источник
How to make a temporary file in RAM?
I have a script that will pipe its output to |tee scriptnameYYMMDD.txt . After each cycle of the for loop in which the output is generated, I’ll be reversing the file contents with tac scriptnameYYYYMMDD.txt > /var/www/html/logs/scriptname.txt so that the log output is visible in a browser window with the newest lines at the top.
I’ll have several scripts doing this in parallel. I’m trying to minimize the disk activity, so output from |tee scriptnameYYYYMMDD.txt to a RAMdisk would be best. mktemp creates a file in the /tmp folder, but that doesn’t appear to be off-disk.
4 Answers 4
You can mount a tmpfs partititon and write the file there:
This partition now is limited to 500 MB. If your temporary file grows larger than 500 MB an error will occur: no space left on device . But, it doesn’t matter when you specify a larger amount of space than your systems RAM has. tmpfs uses swap space too, so you cannot force a system crash, as opposed to ramfs .
You can now write your file into /mountpoint :
The following answer was discovered by investigating the previous answers and the info in this question here and would not have been found without them. Cudos to them.
On my linuxmint system (and I would assume most ubuntu based systems and possibly debian based too) there is a user owned tmpfs mounted automatically on /run/user/1000/
Use df -T to check.
Under /run/user/ there is a directory for each normal user on the system
These directories are named after their respective user’s ids. We can get the user id with id -u see man id for details on this command.
We can then use the mktemp command with the —tmpdir option to create temp files and directories in this tempfilesystem thus creating tempfiles in RAM.
Following the advice given here I create a temp directory first and then create my temp files in that:
to create a temp directory /run/user/1000/bash.w42BYxbG/ then
to create a tempfile in it.
This makes cleaning up these file easy since all I have to do is rm -r $mydir .
By default all these files are owned and readable only by the user who created them.
Источник