summaryrefslogtreecommitdiff
path: root/src/basic
diff options
context:
space:
mode:
authorLennart Poettering <lennart@poettering.net>2016-12-01 23:19:31 +0100
committerLennart Poettering <lennart@poettering.net>2016-12-07 18:38:41 +0100
commit676bcb0fc042c24e4335832622ea4104a1295b48 (patch)
tree21f04994c40f12328d35db1214325169a91da467 /src/basic
parent2d8457851b85813724b1b8b8c7a49c1c4200dd45 (diff)
util-lib: add easy helpers for temporary directories that rmdir()ed via _cleanup_
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.
Diffstat (limited to 'src/basic')
-rw-r--r--src/basic/fileio.c19
-rw-r--r--src/basic/fileio.h2
-rw-r--r--src/basic/fs-util.h7
3 files changed, 28 insertions, 0 deletions
diff --git a/src/basic/fileio.c b/src/basic/fileio.c
index 1615456659..c43b0583a4 100644
--- a/src/basic/fileio.c
+++ b/src/basic/fileio.c
@@ -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;
+}
diff --git a/src/basic/fileio.h b/src/basic/fileio.h
index b58c83e64a..17b38a5d60 100644
--- a/src/basic/fileio.h
+++ b/src/basic/fileio.h
@@ -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);
diff --git a/src/basic/fs-util.h b/src/basic/fs-util.h
index 0d925c6b84..5fe5c71ff0 100644
--- a/src/basic/fs-util.h
+++ b/src/basic/fs-util.h
@@ -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);