mkstemp
In
tmpnam()
was deprecated,[1] because the latter carried the risk that a temporary file with the same name could be created by another thread or process within the time from when the caller obtains the temporary filename and attempts to create it.[2] mkstemp
does not suffer from this problem.[3]Usage
Inclusion
- C
#include <stdlib.h> // per IEEE Std 1003.1, 2004
#include <unistd.h> // for "legacy" systems
- C++
#include <cstdlib> // per IEEE Std 1003.1, 2004
#include <unistd.h> // for "legacy" systems
Declaration
int mkstemp(char* template);
Requirements
- The parameter
template
must be a modifiable, null-terminated character array. - The contents of
template
must be in the format of a valid file path, with six trailing 'X's. - The parameter
template
must not have been used in a previous invocation ofmkstemp
.
Semantics
- The trailing 'X's in
template
are overwritten to generate a unique file name for the resulting temporary file. - The function reports a valid file descriptor to a temporary file on success; on failure, it reports
-1
.
Example
The following code is an example of the usage of mkstemp
; the local variable filename
is modified by mkstemp
and will contain the path to the new file:[4]
#include <stdlib.h>
void example()
{
char filename[] = "/tmp/prefXXXXXX";
mkstemp(filename);
}
Error conditions
It is unspecified if mkstemp
sets
Mechanism
The mkstemp
function generates a filename according to the supplied argument for the template, and attempts to create it. It repeats this process until a file has been successfully created.[5] After this, it opens the file and returns the file descriptor to the caller,[6] with the data buffer that was passed to the function with the template now containing the new filename.[7] The file can be deleted immediately after the mkstemp
call returns to prevent other processes from opening it, but the file can still be used because the calling process will still have a valid file descriptor.[5] Older versions of mkstemp
created the file with an umask of 0666, resulting in the temporary files being readable and writable to all users, and thus presenting a security vulnerability; this is mitigated by setting the umask manually before calling mkstemp
.[6] Newer versions of the function create the file with the umask 600, so that only the owner of the file may read from and write to it.[7]
See also
- tmpfile
References
- ^ OpenGroup
- OpenGroup. 2018.
- )
- )
- ^ )
- ^ Network and Distributed System Security Symposium. 4. Internet Society. Archived(PDF) from the original on 2015-10-08. Retrieved 2019-05-18.
- ^ S2CID 239879. Archived from the original(PDF) on 2019-03-05. Retrieved 2019-05-18.