summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorH. Peter Anvin <hpa@zytor.com>2007-01-15 01:11:26 -0800
committerH. Peter Anvin <hpa@zytor.com>2007-01-15 01:11:26 -0800
commit059de7ce20e446987f4a7c16e60760b86d383860 (patch)
tree5a089acacf4f2f01486a44612cd9af158f17ba16 /lib
parent6124dcbe2d7c5915bd08117e572469754ec331eb (diff)
downloadtftp-hpa-059de7ce20e446987f4a7c16e60760b86d383860.tar.gz
Use replacement library functions to daemonize, rather than #ifdef hell
Diffstat (limited to 'lib')
-rw-r--r--lib/daemon.c37
-rw-r--r--lib/dup2.c25
2 files changed, 62 insertions, 0 deletions
diff --git a/lib/daemon.c b/lib/daemon.c
new file mode 100644
index 0000000..c3106b5
--- /dev/null
+++ b/lib/daemon.c
@@ -0,0 +1,37 @@
+/*
+ * 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
+}
diff --git a/lib/dup2.c b/lib/dup2.c
new file mode 100644
index 0000000..bdf3325
--- /dev/null
+++ b/lib/dup2.c
@@ -0,0 +1,25 @@
+/*
+ * dup2.c
+ *
+ * Ersatz dup2() for really ancient systems
+ */
+
+#include "config.h"
+
+int dup2(int oldfd, int newfd)
+{
+ int rv, nfd;
+
+ close(newfd);
+
+ nfd = rv = dup(oldfd);
+
+ if (rv >= 0 && rv != newfd) {
+ rv = dup2(oldfd, newfd);
+ close(nfd);
+ }
+
+ return rv;
+}
+
+