Mercurial > syslog2iptables
diff src/daemon.c @ 44:9e9f09cf411c
Add fixes for Solaris from sm-archive.
author | Carl Byington <carl@five-ten-sg.com> |
---|---|
date | Sat, 22 Mar 2008 10:58:24 -0700 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/daemon.c Sat Mar 22 10:58:24 2008 -0700 @@ -0,0 +1,61 @@ +/*Add by Sergey Shapovalov */ +#include <unistd.h> +#include <stdlib.h> +#include <fcntl.h> +#include <signal.h> +#include <sys/types.h> +#include <sys/wait.h> +#include <errno.h> + +/* closeall() -- close all FDs >= a specified value */ + +void closeall(int fd) +{ + int fdlimit = sysconf(_SC_OPEN_MAX); + + while (fd < fdlimit) + close(fd++); +} + +/* daemon() - detach process from user and disappear into the background + * returns -1 on failure, but you can't do much except exit in that case + * since we may already have forked. This is based on the BSD version, + * so the caller is responsible for things like the umask, etc. + */ + +/* believed to work on all Posix systems */ + +int daemon(int nochdir, int noclose) +{ + switch (fork()) + { + case 0: break; + case -1: return -1; + default: _exit(0); /* exit the original process */ + } + + if (setsid() < 0) /* shoudn't fail */ + return -1; + + /* dyke out this switch if you want to acquire a control tty in */ + /* the future -- not normally advisable for daemons */ + + 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; +}