When a file created with mkstemp() is deleted? When a file created with mkstemp() is deleted? linux linux

When a file created with mkstemp() is deleted?


will Linux delete this file after close(fd)?

Not automatically. You need to call unlink on the file manually. You can do this immediately after calling mkstemp if you don’t need to access the file by name (i.e. via the file system) — it will then be deleted once the descriptor is closed.

Alternatively, if you need to pass the file on to another part of the code (or process) by name, don’t call unlink just yet.

Here’s an example workflow:

char filename[] = "tempfile-XXXXXX";int fd;if ((fd = mkstemp(filename)) == -1) {    fprintf(stderr, "Failed with error %s\n", strerror(errno));    return -1;}unlink(filename);FILE *fh = fdopen(fd, "w");fprintf(fh, "It worked!\n");fclose(fh);

fclose closes the FILE* stream, but also the underlying file descriptor, so we don’t need to explicitly call close(fd).

Necessary headers:

#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>


No, when a file is created with tmpfile(), its directory entry (in the temporary directory) is removed after the creation, so there is only the file descriptor referenced by open that leads to the file inodes (in the /proc/<pid>/fd directory); once you call close(fd), there are no more reference to the file.

With mkstemp() you have to do it manually with unlink() right after the creation.


The Linux Programming Interface book gives best answer to this question. Regard the comments in the code below.

Typically, a temporary file is unlinked (deleted) soon after it is opened, using the unlink() system call (Section 18.3). Thus, we could employ mkstemp() as follows:

int fd;char template[] = "/tmp/somestringXXXXXX";fd = mkstemp(template);if (fd == -1)    errExit("mkstemp");    printf("Generated filename was: %s\n", template);    unlink(template);    /* Name disappears immediately, but the file    is removed only after close() */    /* Use file I/O system calls - read(), write(), and so on */if (close(fd) == -1)    errExit("close");