]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/daemon.c
b5ced0cb795e48cdd239d24a2fbdcdaa4db56120
[bacula/bacula] / bacula / src / lib / daemon.c
1 /*
2  *  daemon.c by Kern Sibbald
3  *
4  *   Version $Id$
5  *
6  *   this code is inspired by the Prentice Hall book
7  *   "Unix Network Programming" by W. Richard Stevens
8  *   and later updated from his book "Advanced Programming
9  *   in the UNIX Environment"
10  *
11  * Initialize a daemon process completely detaching us from
12  * any terminal processes. 
13  *
14  */ 
15
16 /*
17    Copyright (C) 2000, 2001, 2002 Kern Sibbald and John Walker
18
19    This program is free software; you can redistribute it and/or
20    modify it under the terms of the GNU General Public License as
21    published by the Free Software Foundation; either version 2 of
22    the License, or (at your option) any later version.
23
24    This program is distributed in the hope that it will be useful,
25    but WITHOUT ANY WARRANTY; without even the implied warranty of
26    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
27    General Public License for more details.
28
29    You should have received a copy of the GNU General Public
30    License along with this program; if not, write to the Free
31    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
32    MA 02111-1307, USA.
33
34  */
35
36
37 #include "bacula.h"
38
39 void 
40 daemon_start()
41 {
42 #ifndef HAVE_CYGWIN
43    int i;
44    int cpid;
45    mode_t oldmask;
46    /*
47     *  Become a daemon.
48     */
49
50    Dmsg0(200, "Enter daemon_start\n");
51    if ( (cpid = fork() ) < 0)
52       Emsg1(M_ABORT, 0, "Cannot fork to become daemon: %s\n", strerror(errno));
53    else if (cpid > 0)
54       exit(0);              /* parent exits */
55    /* Child continues */
56       
57    setsid();
58
59    /* In the PRODUCTION system, we close ALL
60     * file descriptors. It is useful
61     * for debugging to leave the STDOUT ane STDERR open.
62     */
63    for (i=sysconf(_SC_OPEN_MAX)-1; i >=0; i--) {
64 #ifdef DEBUG
65       if (i != STDOUT_FILENO && i != STDERR_FILENO) {
66          close(i);
67       }
68 #else 
69       close(i);
70 #endif
71    }
72
73    /* Move to root directory. For debug we stay
74     * in current directory so dumps go there.
75     */
76 #ifndef DEBUG
77    chdir("/");
78 #endif
79
80    /* 
81     * Avoid creating files 666 but don't override any
82     * more restrictive mask set by the user.
83     */
84    oldmask = umask(026);
85    oldmask |= 026;
86    umask(oldmask);
87
88    Dmsg0(200, "Exit daemon_start\n");
89 #endif /* HAVE_CYGWIN */
90 }