]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/daemon.c
ebl add sql_escape to catalog messages
[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    Copyright (C) 2000-2005 Kern Sibbald
17
18    This program is free software; you can redistribute it and/or
19    modify it under the terms of the GNU General Public License
20    version 2 as amended with additional clauses defined in the
21    file LICENSE in the main source directory.
22
23    This program is distributed in the hope that it will be useful,
24    but WITHOUT ANY WARRANTY; without even the implied warranty of
25    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
26    the file LICENSE for additional details.
27
28  */
29
30
31 #include "bacula.h"
32 extern int debug_level;
33
34 void
35 daemon_start()
36 {
37 #if !defined(HAVE_WIN32)
38    int i;
39    pid_t cpid;
40    mode_t oldmask;
41 #ifdef DEVELOPER
42    int low_fd = 2;
43 #else
44    int low_fd = -1;
45 #endif
46    /*
47     *  Become a daemon.
48     */
49
50    Dmsg0(900, "Enter daemon_start\n");
51    if ( (cpid = fork() ) < 0) {
52       berrno be;
53       Emsg1(M_ABORT, 0, _("Cannot fork to become daemon: %s\n"), be.strerror());
54    } else if (cpid > 0) {
55       exit(0);              /* parent exits */
56    }
57    /* Child continues */
58
59    setsid();
60
61    /* In the PRODUCTION system, we close ALL
62     * file descriptors except stdin, stdout, and stderr.
63     */
64    if (debug_level > 0) {
65       low_fd = 2;                     /* don't close debug output */
66    }
67    for (i=sysconf(_SC_OPEN_MAX)-1; i > low_fd; i--) {
68       close(i);
69    }
70
71    /* Move to root directory. For debug we stay
72     * in current directory so dumps go there.
73     */
74 #ifndef DEBUG
75    chdir("/");
76 #endif
77
78    /*
79     * Avoid creating files 666 but don't override any
80     * more restrictive mask set by the user.
81     */
82    oldmask = umask(026);
83    oldmask |= 026;
84    umask(oldmask);
85
86
87    /*
88     * Make sure we have fd's 0, 1, 2 open
89     *  If we don't do this one of our sockets may open
90     *  there and if we then use stdout, it could
91     *  send total garbage to our socket.
92     *
93     */
94    int fd;
95    fd = open("/dev/null", O_RDONLY, 0644);
96    if (fd > 2) {
97       close(fd);
98    } else {
99       for(i=1; fd + i <= 2; i++) {
100          dup2(fd, fd+i);
101       }
102    }
103
104 #endif /* HAVE_WIN32 */
105    Dmsg0(900, "Exit daemon_start\n");
106 }