Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a file created with mkstemp() is deleted?

I have a program that calls mkstemp(), writes some stuff with the fd returned and then closes the fd. I want the file to remain until I delete it myself! With something like rm command, or whatever. My question is: will Linux delete this file after close(fd)?

like image 485
matheuscscp Avatar asked Sep 07 '15 20:09

matheuscscp


1 Answers

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>
like image 147
Konrad Rudolph Avatar answered Oct 13 '22 17:10

Konrad Rudolph