From 2d8a35e2eb9b93aafe0a86e45bb4cb0abf8b6c3a Mon Sep 17 00:00:00 2001 From: =?utf8?q?Zbigniew=20J=C4=99drzejewski-Szmek?= Date: Wed, 16 May 2018 11:35:41 +0200 Subject: [PATCH] fs-util,test: add helper to remove tempfiles This simplifies the use of tempfiles in tests and fixes "leaked" temporary files in test-fileio, test-catalog, test-conf-parser. Not the whole tree is converted. --- src/basic/fs-util.c | 9 +++++++++ src/basic/fs-util.h | 1 + src/test/test-conf-parser.c | 3 ++- 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/basic/fs-util.c b/src/basic/fs-util.c index 4e74cb7b0..24c447036 100644 --- a/src/basic/fs-util.c +++ b/src/basic/fs-util.c @@ -1081,6 +1081,15 @@ int access_fd(int fd, int mode) { return r; } +void unlink_tempfilep(char (*p)[]) { + /* If the file is created with mkstemp(), it will (almost always) + * change the suffix. Treat this as a sign that the file was + * successfully created. We ignore both the rare case where the + * original suffix is used and unlink failures. */ + if (!endswith(*p, ".XXXXXX")) + (void) unlink(*p); +} + int unlinkat_deallocate(int fd, const char *name, int flags) { _cleanup_close_ int truncate_fd = -1; struct stat st; diff --git a/src/basic/fs-util.h b/src/basic/fs-util.h index b5bc5c3bc..a337b5f5c 100644 --- a/src/basic/fs-util.h +++ b/src/basic/fs-util.h @@ -122,6 +122,7 @@ DEFINE_TRIVIAL_CLEANUP_FUNC(char*, unlink_and_free); int access_fd(int fd, int mode); +void unlink_tempfilep(char (*p)[]); int unlinkat_deallocate(int fd, const char *name, int flags); int fsync_directory_of_file(int fd); diff --git a/src/test/test-conf-parser.c b/src/test/test-conf-parser.c index 76419a74b..85954e097 100644 --- a/src/test/test-conf-parser.c +++ b/src/test/test-conf-parser.c @@ -8,6 +8,7 @@ #include "conf-parser.h" #include "fd-util.h" #include "fileio.h" +//#include "fs-util.h" #include "log.h" #include "macro.h" #include "string-util.h" @@ -329,7 +330,7 @@ static const char* const config_file[] = { }; static void test_config_parse(unsigned i, const char *s) { - char name[] = "/tmp/test-conf-parser.XXXXXX"; + _cleanup_(unlink_tempfilep) char name[] = "/tmp/test-conf-parser.XXXXXX"; int fd, r; _cleanup_fclose_ FILE *f = NULL; _cleanup_free_ char *setting1 = NULL; -- 2.30.2