2 * daemon.c by Kern Sibbald
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"
11 * Initialize a daemon process completely detaching us from
12 * any terminal processes.
17 Copyright (C) 2000-2004 Kern Sibbald and John Walker
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.
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.
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,
42 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
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));
54 exit(0); /* parent exits */
59 /* In the PRODUCTION system, we close ALL
60 * file descriptors except stdin, stdout, and stderr.
62 for (i=sysconf(_SC_OPEN_MAX)-1; i > 2; i--) {
66 /* Move to root directory. For debug we stay
67 * in current directory so dumps go there.
74 * Avoid creating files 666 but don't override any
75 * more restrictive mask set by the user.
81 Dmsg0(200, "Exit daemon_start\n");
84 * Make sure we have fd's 0, 1, 2 open
85 * If we don't do this one of our sockets may open
86 * there and if we then use stdout, it could
87 * send total garbage to our socket.
91 fd = open("/dev/null", O_RDONLY, 0644);
95 for(i=1; fd + i <= 2; i++) {
100 #endif /* HAVE_CYGWIN */