From d62a6dd804cabfe12c37365bcd2007a232cdc775 Mon Sep 17 00:00:00 2001 From: wens Date: Thu, 21 Aug 2008 02:01:03 +0000 Subject: Common daemonize function git-svn-id: http://opensvn.csie.org/pttbbs/trunk/pttbbs@4399 63ad8ddf-47c3-0310-b6dd-a9e9d9715204 --- common/sys/Makefile | 2 +- common/sys/daemon.c | 90 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 common/sys/daemon.c (limited to 'common') diff --git a/common/sys/Makefile b/common/sys/Makefile index fe9fb2dc..adace886 100644 --- a/common/sys/Makefile +++ b/common/sys/Makefile @@ -5,7 +5,7 @@ MKPIC:=no SRCROOT= ../.. .include "$(SRCROOT)/pttbbs.mk" -SRCS:= file.c lock.c log.c net.c sort.c string.c time.c crypt.c record.c vector.c +SRCS:= daemon.c file.c lock.c log.c net.c sort.c string.c time.c crypt.c record.c vector.c LIB:= cmsys all: .depend diff --git a/common/sys/daemon.c b/common/sys/daemon.c new file mode 100644 index 00000000..829d0a9c --- /dev/null +++ b/common/sys/daemon.c @@ -0,0 +1,90 @@ +/* $Id$ */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "osdep.h" +#include "cmsys.h" + +int +daemonize(const char * pidfile, const char * logfile) +{ + int fd; + char buf[32]; + pid_t pid; + + umask(022); + + if ((pid = fork()) < 0) { + perror("Fork failed"); + exit(1); + } + + if (pid > 0) + exit(0); + + if (setsid() < 0) { + perror("Setsid failed"); + exit(-1); + } + + if ((pid = fork()) < 0) { + perror("Fork failed"); + exit(1); + } + + if (pid > 0) + exit(0); + + if (chdir("/") < 0) { + perror("Can't chdir to root"); + exit(-1); + } + + if (pidfile) { + if ((fd = creat(pidfile, 0644)) >= 0) { + snprintf(buf, sizeof(buf), "%d", (int)getpid()); + write(fd, buf, strlen(buf)); + close(fd); + } else + perror("Can't open PID file"); + } + + if (logfile) { + if ((fd = open(logfile, O_WRONLY | O_CREAT | O_APPEND, 0644)) < 0) { + perror("Can't open logfile"); + exit(1); + } + if (fd != 2) { + dup2(fd, 2); + close(fd); + } + } + + fd = getdtablesize(); + while (fd > 2) + close(--fd); + + if ((fd = open("/dev/null", O_RDWR)) < 0) { + perror("Can't open /dev/null"); + exit(1); + } + + dup2(fd, 0); + dup2(fd, 1); + if (!logfile) + dup2(fd, 2); + + if (fd > 2) + close(fd); + + Signal(SIGHUP, SIG_IGN); + Signal(SIGCHLD, SIG_IGN); + + return 0; +} -- cgit v1.2.3