+/* Some functions the less gifted operating systems might lack... */
+
+#ifndef HAVE_FCLOSEALL
+int fcloseall(void)
+{
+ fflush(stdin);
+ fflush(stdout);
+ fflush(stderr);
+ fclose(stdin);
+ fclose(stdout);
+ fclose(stderr);
+}
+#endif
+
+#ifndef HAVE_DAEMON
+int daemon(int nochdir, int noclose)
+{
+ pid_t pid;
+ int fd;
+
+ ppid = getpid();
+
+ if((pid = fork()) < 0)
+ {
+ perror("fork");
+ return -1;
+ }
+ if(pid) /* parent process */
+ {
+ signal(SIGTERM, parent_exit);
+ sleep(600); /* wait 10 minutes */
+ exit(1);
+ }
+
+ if((fd = open("/dev/tty", O_RDWR)) >= 0)
+ {
+ if(ioctl(fd, TIOCNOTTY, NULL))
+ {
+ perror("ioctl");
+ return -1;
+ }
+ close(fd);
+ }
+
+ if(setsid() < 0)
+ return -1;
+
+ kill(ppid, SIGTERM);
+
+ if(!nochdir)
+ chdir("/");
+
+ if(!noclose)
+ fcloseall();
+}
+#endif
+