1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
/* $Id: daemonize.C,v 1.4 2001/10/03 01:45:52 dm Exp $ */
/*
*
* Copyright (C) 1999 David Mazieres (dm@uun.org)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
*/
#include "async.h"
str syslog_priority ("daemon.notice");
static void
start_logger ()
{
#ifdef PATH_LOGGER
char *av[] = { PATH_LOGGER, "-p",
const_cast<char *> (syslog_priority.cstr ()),
"-t", "", NULL};
int fds[2];
if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
fatal ("socketpair: %m\n");
close_on_exec (fds[0]);
if (fds[1] != 0)
close_on_exec (fds[1]);
if (spawn (PATH_LOGGER, av, fds[1]) >= 0) {
close (fds[1]);
if (fds[0] != errfd) {
err_flush (); // XXX - we shouldn't depend on aerr.C
if (dup2 (fds[0], errfd) < 0)
fatal ("dup2: %m\n");
close (fds[0]);
}
if (errfd != 1)
dup2 (errfd, 1);
close (0);
if (int fd = open ("/dev/null", O_RDONLY))
close (fd);
return;
}
else
warn ("%s: %m\n", PATH_LOGGER);
#endif /* PATH_LOGGER */
/* No logger, at least send chatter to stdout rather than stderr, so
* that it can be redirected. */
dup2 (errfd, 1);
}
void
daemonize ()
{
switch (fork ()) {
default:
_exit (0);
case -1:
fatal ("fork: %m\n");
case 0:
break;
}
if (setsid () < 0)
fatal ("setsid: %m\n");
if (!builddir) {
start_logger ();
str2file (strbuf () << PIDDIR << "/" << progname << ".pid",
strbuf ("%d\n", getpid ()), 0444);
}
else {
str piddir = buildtmpdir;
if (!piddir)
piddir = builddir;
str2file (strbuf () << buildtmpdir << "/" << progname << ".pid",
strbuf ("%d\n", getpid ()), 0444);
}
}
|