chiark / gitweb /
util: introduce mkdir_parents() that creates parent paths of sockets and suchlike
authorLennart Poettering <lennart@poettering.net>
Fri, 12 Feb 2010 01:01:14 +0000 (02:01 +0100)
committerLennart Poettering <lennart@poettering.net>
Fri, 12 Feb 2010 01:01:14 +0000 (02:01 +0100)
util.c
util.h

diff --git a/util.c b/util.c
index c5c8bd4edda6d68f1ef88607b9d09c559e42840a..517c99c45ef5cbe9fab4f50a1e53a97527391392 100644 (file)
--- a/util.c
+++ b/util.c
 #include <sched.h>
 #include <sys/resource.h>
 #include <linux/sched.h>
 #include <sched.h>
 #include <sys/resource.h>
 #include <linux/sched.h>
+#include <sys/types.h>
+#include <sys/stat.h>
 
 #include "macro.h"
 #include "util.h"
 #include "ioprio.h"
 #include "missing.h"
 
 #include "macro.h"
 #include "util.h"
 #include "ioprio.h"
 #include "missing.h"
+#include "log.h"
 
 usec_t now(clockid_t clock_id) {
         struct timespec ts;
 
 usec_t now(clockid_t clock_id) {
         struct timespec ts;
@@ -590,6 +593,39 @@ char *file_in_same_dir(const char *path, const char *filename) {
         return r;
 }
 
         return r;
 }
 
+int mkdir_parents(const char *path, mode_t mode) {
+        const char *p, *e;
+
+        assert(path);
+
+        /* Creates every parent directory in the path except the last
+         * component. */
+
+        p = path + strspn(path, "/");
+        for (;;) {
+                int r;
+                char *t;
+
+                e = p + strcspn(p, "/");
+                p = e + strspn(e, "/");
+
+                /* Is this the last component? If so, then we're
+                 * done */
+                if (*p == 0)
+                        return 0;
+
+                if (!(t = strndup(path, e - path)))
+                        return -ENOMEM;
+
+                r = mkdir(t, mode);
+
+                free(t);
+
+                if (r < 0 && errno != EEXIST)
+                        return -errno;
+        }
+}
+
 char hexchar(int x) {
         static const char table[16] = "0123456789abcdef";
 
 char hexchar(int x) {
         static const char table[16] = "0123456789abcdef";
 
diff --git a/util.h b/util.h
index f5cb165559aba4be5f49b697d9db625188805368..ba7e542baa15cac6b8092e3d48985dfc8e635b2f 100644 (file)
--- a/util.h
+++ b/util.h
@@ -127,6 +127,7 @@ int reset_all_signal_handlers(void);
 
 char *strstrip(char *s);
 char *file_in_same_dir(const char *path, const char *filename);
 
 char *strstrip(char *s);
 char *file_in_same_dir(const char *path, const char *filename);
+int mkdir_parents(const char *path, mode_t mode);
 
 char hexchar(int x);
 int unhexchar(char c);
 
 char hexchar(int x);
 int unhexchar(char c);