]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_utilities/lib/daemon.cpp
Security-59754.80.3.tar.gz
[apple/security.git] / OSX / libsecurity_utilities / lib / daemon.cpp
1 /*
2 * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24
25 //
26 // demon - support code for writing UNIXoid demons
27 //
28 #include <security_utilities/daemon.h>
29 #include <security_utilities/logging.h>
30 #include <security_utilities/debugging.h>
31 #include <sys/types.h>
32 #include <errno.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35
36 namespace Security {
37 namespace Daemon {
38
39 //
40 // Daemonize this process, the UNIX way.
41 //
42 bool incarnate(bool doFork /*=true*/)
43 {
44 if (doFork) {
45 // fork with slight resilience
46 for (int forkTries = 1; forkTries <= 5; forkTries++) {
47 switch (fork()) {
48 case 0: // child
49 // we are the daemon process (Har! Har!)
50 break;
51 case -1: // parent: fork failed
52 switch (errno) {
53 case EAGAIN:
54 case ENOMEM:
55 Syslog::warning("fork() short on resources (errno=%d); retrying", errno);
56 sleep(forkTries);
57 continue;
58 default:
59 Syslog::error("fork() failed (errno=%d)", errno);
60 return false;
61 }
62 default: // parent
63 // @@@ we could close an assurance loop here, but we don't (yet?)
64 exit(0);
65 }
66 }
67 // fork succeeded; we are the child; parent is terminating
68 }
69
70 // create new session (the magic set-me-apart system call)
71 setsid();
72
73 // redirect standard channels to /dev/null
74 close(0); // fail silently in case 0 is closed
75 if (open("/dev/null", O_RDWR, 0) == 0) { // /dev/null could be missing, I suppose...
76 dup2(0, 1);
77 dup2(0, 2);
78 }
79
80 // ready to roll
81 return true;
82 }
83
84 } // end namespace Daemon
85 } // end namespace Security