When a file created with mkstemp() is deleted?

杀马特。学长 韩版系。学妹 提交于 2019-12-10 13:56:11

问题


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)?


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/32445579/when-a-file-created-with-mkstemp-is-deleted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!