/***********************************************************************1* *2* This software is part of the ast package *3* Copyright (c) 1990-2011 AT&T Intellectual Property *4* and is licensed under the *5* Eclipse Public License, Version 1.0 *6* by AT&T Intellectual Property *7* *8* A copy of the License is available at *9* http://www.eclipse.org/org/documents/epl-v10.html *10* (with md5 checksum b35adb5213ca9657e911e9befb180842) *11* *12* Information and Software Systems Research *13* AT&T Research *14* Florham Park NJ *15* *16* Glenn Fowler <[email protected]> *17* *18***********************************************************************/19#pragma prototyped2021/*22* Glenn Fowler23* AT&T Research24*25* slip into the background26* (1<<fd) bits not in fds will be modified:27* 0-2 dup'd to /dev/null28* 3-sysconf(_SC_OPEN_MAX) closed29*30* daemon details thanks to31* "UNIX Network Programming, W. Richard Stevens, Prentice Hall, 1990"32*/3334#include "cslib.h"3536#include <sig.h>3738int39csdaemon(register Cs_t* state, int fds)40{41register int fd;42register int i;43int oerrno;4445messagef((state->id, NiL, -8, "daemon(%o) call", fds));46oerrno = errno;4748/*49* unconditionally ignore some signals50*/5152signal(SIGHUP, SIG_IGN);53#ifdef SIGTTOU54signal(SIGTTOU, SIG_IGN);55#endif56#ifdef SIGTTIN57signal(SIGTTIN, SIG_IGN);58#endif59#ifdef SIGTSTP60signal(SIGTSTP, SIG_IGN);61#endif6263/*64* generate some children if not scheduled from init65*/6667if (getppid() > 1)68{69#if _lib_fork70if (!(state->flags & CS_DAEMON_SLAVE)) switch (fork())71{72case -1:73return -1;74case 0:75systrace(NiL);76break;77default:78/*79* allow some time for service setup80*/8182sleep(2);83exit(0);84}85#endif8687/*88* become process group leader and drop control tty89*/9091setsid();92}9394/*95* redirect {0,1,2} to /dev/null if not in fds96*/9798if ((fds & ((1<<0)|(1<<1)|(1<<2))) != ((1<<0)|(1<<1)|(1<<2)) && (fd = open("/dev/null", O_RDWR)) >= 0)99{100fds |= (1<<fd);101for (i = 0; i <= 2; i++)102if (!(fds & (1<<i)))103{104close(i);105dup(fd);106}107close(fd);108}109110/*111* close any other garbage fds112*/113114for (i = 3; i < 20; i++)115if (!(fds & (1<<i)) && !fcntl(i, F_GETFD, 0))116close(i);117118/*119* avoid unexpected permission problems120*/121122umask(0);123124/*125* no command-relative relative root searching126*/127128pathpath(NiL, "", 0, NiL, 0);129130/*131* we ignored a lot of errors to get here132*/133134errno = oerrno;135messagef((state->id, NiL, -8, "daemon(%o) = 0", fds));136return 0;137}138139int140_cs_daemon(int fds)141{142return csdaemon(&cs, fds);143}144145146