summaryrefslogtreecommitdiffstats
path: root/lib/daemon.c
diff options
context:
space:
mode:
Diffstat (limited to 'lib/daemon.c')
-rw-r--r--lib/daemon.c36
1 files changed, 36 insertions, 0 deletions
diff --git a/lib/daemon.c b/lib/daemon.c
new file mode 100644
index 0000000..0eb39c9
--- /dev/null
+++ b/lib/daemon.c
@@ -0,0 +1,36 @@
+/*
+ * daemon.c - "daemonize" a process
+ */
+
+#include "config.h"
+
+int daemon(int nochdir, int noclose)
+{
+ int nullfd;
+ pid_t f;
+
+ if (!nochdir) {
+ if (chdir("/"))
+ return -1;
+ }
+
+ if (!noclose) {
+ if ((nullfd = open("/dev/null", O_RDWR)) < 0 ||
+ dup2(nullfd, 0) < 0 ||
+ dup2(nullfd, 1) < 0 || dup2(nullfd, 2) < 0)
+ return -1;
+ close(nullfd);
+ }
+
+ f = fork();
+ if (f < 0)
+ return -1;
+ else if (f > 0)
+ _exit(0);
+
+#ifdef HAVE_SETSID
+ return setsid();
+#else
+ return 0;
+#endif
+}