chiark / gitweb /
util-lib: add easy helpers for temporary directories that rmdir()ed via _cleanup_
authorLennart Poettering <lennart@poettering.net>
Thu, 1 Dec 2016 22:19:31 +0000 (23:19 +0100)
committerSven Eden <yamakuzure@gmx.net>
Mon, 17 Jul 2017 15:58:35 +0000 (17:58 +0200)
This adds mkdtemp_malloc() that is a combination of mkdtemp() plus strdup(). It
initializes its return paremeter only if the temporary directory could be
created successfully, so that the parameter is exactly non-NULL when the
directory exists.

rmdir_and_free() and rmdir_and_freep() are also added, and the latter may be
used inside of _cleanup_ for such a directory string variable, to automatically
rmdir() the directory if it is non-NULL when the scope exits.

rmdir_and_free() is similar to the existing rm_rf_and_free() however, is only
removes a single directory and does not operate recursively.

src/basic/fileio.c
src/basic/fileio.h
src/basic/fs-util.h

index f4915b28a7092f91d2c3d7ae5f8c2582738b5cf6..8241e656addefef6263b832389fbb46a60974140 100644 (file)
@@ -1414,3 +1414,22 @@ int read_nul_string(FILE *f, char **ret) {
 
         return 0;
 }
+
+int mkdtemp_malloc(const char *template, char **ret) {
+        char *p;
+
+        assert(template);
+        assert(ret);
+
+        p = strdup(template);
+        if (!p)
+                return -ENOMEM;
+
+        if (!mkdtemp(p)) {
+                free(p);
+                return -errno;
+        }
+
+        *ret = p;
+        return 0;
+}
index 6a628086bce173d47a6f38e702e8431e1f1f6011..062aeed2e766c0129f92d9c4d7c7521b880ad54b 100644 (file)
@@ -49,8 +49,6 @@ int parse_env_file(const char *fname, const char *separator, ...) _sentinel_;
 int load_env_file(FILE *f, const char *fname, const char *separator, char ***l);
 int load_env_file_pairs(FILE *f, const char *fname, const char *separator, char ***l);
 
-int merge_env_file(char ***env, FILE *f, const char *fname);
-
 int write_env_file(const char *fname, char **l);
 
 int executable_is_script(const char *path, char **interpreter);
@@ -96,3 +94,5 @@ int link_tmpfile(int fd, const char *path, const char *target);
 #endif // 0
 
 int read_nul_string(FILE *f, char **ret);
+
+int mkdtemp_malloc(const char *template, char **ret);
index d925cc2d054086ec70e34d363060d52cf036acd5..3f47537de147fb2b0689cc89f238f3596ccf7f16 100644 (file)
@@ -97,3 +97,10 @@ enum {
 };
 
 int chase_symlinks(const char *path_with_prefix, const char *root, unsigned flags, char **ret);
+
+/* Useful for usage with _cleanup_(), removes a directory and frees the pointer */
+static inline void rmdir_and_free(char *p) {
+        (void) rmdir(p);
+        free(p);
+}
+DEFINE_TRIVIAL_CLEANUP_FUNC(char*, rmdir_and_free);