]> arthur.barton.de Git - netatalk.git/blobdiff - libatalk/util/unix.c
Merge master
[netatalk.git] / libatalk / util / unix.c
index ab0c25e53cf7669f90409a20b50ebf308c71b223..0ac210ec2c8d4e3e1d99ab16a33f7067cfabd24f 100644 (file)
 #include <atalk/vfs.h>
 #include <atalk/util.h>
 #include <atalk/unix.h>
+#include <atalk/compat.h>
+
+/* close all FDs >= a specified value */
+static void closeall(int fd)
+{
+    int fdlimit = sysconf(_SC_OPEN_MAX);
+
+    while (fd < fdlimit)
+        close(fd++);
+}
+
+/*!
+ * Daemonize
+ *
+ * Fork, exit parent, setsid(), optionally chdir("/"), optionally close all fds
+ *
+ * returns -1 on failure, but you can't do much except exit in that case
+ * since we may already have forked
+ */
+int daemonize(int nochdir, int noclose)
+{
+    switch (fork()) {
+    case 0:
+        break;
+    case -1:
+        return -1;
+    default:
+        _exit(0);
+    }
+
+    if (setsid() < 0)
+        return -1;
+
+    switch (fork()) {
+    case 0: 
+        break;
+    case -1:
+        return -1;
+    default:
+        _exit(0);
+    }
+
+    if (!nochdir)
+        chdir("/");
+
+    if (!noclose) {
+        closeall(0);
+        open("/dev/null",O_RDWR);
+        dup(0);
+        dup(0);
+    }
+
+    return 0;
+}
 
 /*!
  * @brief get cwd in static buffer
@@ -58,28 +112,25 @@ const char *getcwdpath(void)
 }
 
 /*!
- * Make argument path absoulte
+ * @brief Request absolute path
  *
- * @returns pointer to path or pointer to error messages on error
+ * @returns Absolute filesystem path to object
  */
-const char *abspath(const char *name)
+const char *fullpathname(const char *name)
 {
-    static char buf[MAXPATHLEN + 1];
-    char *p;
-    int n;
+    static char wd[MAXPATHLEN + 1];
 
     if (name[0] == '/')
         return name;
 
-    if ((p = getcwd(buf, MAXPATHLEN)) == NULL)
-        return strerror(errno);
+    if (getcwd(wd , MAXPATHLEN)) {
+        strlcat(wd, "/", MAXPATHLEN);
+        strlcat(wd, name, MAXPATHLEN);
+    } else {
+        strlcpy(wd, name, MAXPATHLEN);
+    }
 
-    n = strlen(buf);
-    if (buf[n-1] != '/')
-        buf[n++] = '/';
-        
-    strlcpy(buf + n, name, MAXPATHLEN - n);
-    return buf;
+    return wd;
 }
 
 /*!