]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
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)
committerLennart Poettering <lennart@poettering.net>
Wed, 7 Dec 2016 17:38:41 +0000 (18:38 +0100)
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 1615456659ef29b6a3d6507516ea6574e6315fc2..c43b0583a4a93e6f28658d9de84ae063e4efc98b 100644 (file)
@@ -1409,3 +1409,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 b58c83e64ad501a7322aeff754e2b9f7239cf1fd..17b38a5d60e5567a8fb6e9ea379de644676eabe1 100644 (file)
@@ -88,3 +88,5 @@ int open_tmpfile_linkable(const char *target, int flags, char **ret_path);
 int link_tmpfile(int fd, const char *path, const char *target);
 
 int read_nul_string(FILE *f, char **ret);
+
+int mkdtemp_malloc(const char *template, char **ret);
index 0d925c6b84db82250601e3a21fe6cc1cfc5d8c04..5fe5c71ff029cc953b669fd2e0d3ac427f14dd13 100644 (file)
@@ -84,3 +84,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);