Use mkstemp() instead of mktemp() for Unix temp files
mkstemp() atomically creates and opens a temporary file, closing the time-of-check-to-time-of-use race that mktemp() and tmpnam() leave open.
10 Jun 2026, 03:42 UTC

The race your temporary file name creates
You need a scratch file in a C program, so you call mktemp("/tmp/app.XXXXXX"). It checks whether a name is available, fills in the X characters, and returns that name. Your program then opens the returned path to write data. Between the check and the open, another user or process on the same system can create a symbolic link at that path, pointing it at a sensitive file such as /etc/passwd. Your program follows the link and overwrites the target.
This is a time-of-check-to-time-of-use (TOCTOU) race: the program checks a condition, then acts on it, but the state changes in between. tmpnam() has similar problems, plus a static return buffer and a small pool of possible names. On shared Unix systems, especially where /tmp is world-writable, that window is exploitable.
The useful takeaway is to let the kernel create the file and return an open descriptor in one step, so there is no separate name to guess or pre-create.
Why mkstemp() closes the window
mkstemp() is declared in <stdlib.h> and is part of POSIX.1-2008. You pass it a writable character array ending in XXXXXX, such as char template[] = "/tmp/app.XXXXXX";. The function replaces the trailing X characters with unique letters and atomically opens the file using O_CREAT | O_EXCL. If the name already exists, the call fails with EEXIST; there is no moment when the name exists without an open file attached to it.
The returned descriptor is opened for reading and writing. The initial mode is 0600, but your process umask can remove permissions, so do not assume owner-only access. Verify the actual mode with fstat() after the call.
A critical detail: the template must be a modifiable array, not a string literal. Passing "/tmp/app.XXXXXX" directly is undefined behavior on some implementations because mkstemp() writes into the buffer.
Worked example: create, inspect, unlink, then close
Compile this example as a normal user on Linux, BSD, or macOS. The program needs write permission in /tmp, which is usually available.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(void) {
char template[] = "/tmp/demo.XXXXXX";
int fd = mkstemp(template);
if (fd == -1) {
perror("mkstemp");
return 1;
}
struct stat st;
if (fstat(fd, &st) == -1) {
perror("fstat");
close(fd);
return 1;
}
printf("created name: %s\n", template);
printf("permission bits: %o\n", st.st_mode & 0777);
/* Remove the name while keeping the descriptor open. */
if (unlink(template) == -1) {
perror("unlink");
close(fd);
return 1;
}
int again = open(template, O_RDONLY);
printf("reopen after unlink: %d (expect -1, errno ENOENT)\n", again);
close(fd);
return 0;
}
Build and run it from a terminal:
cc -o mkstemp_demo mkstemp_demo.c
./mkstemp_demo
Expected checks: the program prints the generated name, permission bits that are typically 0600 unless your umask changes them, and -1 for the reopen after unlink(). The reopen failure confirms the directory entry is gone while the descriptor remains valid.
Risks: do not pass a string literal as the template; handle EEXIST, EINTR, ENOSPC, and permission failures explicitly; and do not assume the name is unguessable on every C library. On older systems, check man mkstemp for required feature-test macros such as _DEFAULT_SOURCE.
Cleanup pattern and remaining limits
A common pattern is to call unlink() immediately after mkstemp(), while the descriptor is still open. The file content stays reachable through the descriptor, and the storage is reclaimed when you call close(), even if the process crashes before exiting cleanly. If you abort before unlink(), close the descriptor and remove the pathname to avoid leaving a scratch file behind.
mkstemp() creates a file; it is not a lock. Do not use it as a cross-process coordination mechanism. Combine it with fcntl() or flock() advisory locking only where your target system supports it, and remember that NFS does not honor locking semantics uniformly. mkstemp() also does not pick a directory for you; include a path such as $TMPDIR/app.XXXXXX or /tmp/app.XXXXXX.
Finally, fsync() on the temporary file does not always guarantee that the directory entry is durable after a crash; directory fsync behavior is implementation-specific.
Practical verification
Run the example above and confirm the reopen returns -1. To verify the atomic creation flags, run the program under a system-call tracer such as strace on Linux or truss on BSD and look for an openat() or open() call using O_CREAT | O_EXCL. Repeat on each target operating system, because flags and directory durability can differ. Check man mkstemp and <stdlib.h> on the target system to confirm the prototype and availability.
Bottom line
Prefer mkstemp() whenever your Unix program needs a temporary file. Use a writable XXXXXX template array, check the descriptor and fstat() the result, unlink the name right away if you do not need it in the filesystem, and close the descriptor when you are done. Treat mktemp() and tmpnam() as legacy interfaces to avoid in new code.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.