4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
22 * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
23 * Use is subject to license terms.
29 #pragma ident "%Z%%M% %I% %E% SMI"
33 #include <sys/param.h>
34 #include <sys/types.h>
37 #include <stdio_ext.h>
47 * The parent never returns from this function. It sits
48 * and waits for the child to send status on whether it
51 * We do not close down the standard file descriptors until
52 * we know the child is going to run.
62 * Block all signals prior to the fork and leave them blocked in the
63 * parent so we don't get in a situation where the parent gets SIGINT
64 * and returns non-zero exit status and the child is actually running.
65 * In the child, restore the signal mask once we've done our setsid().
67 (void) sigfillset(&set
);
68 (void) sigdelset(&set
, SIGABRT
);
69 (void) sigprocmask(SIG_BLOCK
, &set
, &oset
);
72 * We need to do this before we open the pipe - it makes things
73 * easier in the long run.
75 closefrom(STDERR_FILENO
+ 1);
77 if (pipe(pfds
) == -1) {
78 fprintf(stderr
, "failed to create pipe for daemonize");
79 exit(SMF_EXIT_ERR_FATAL
);
82 if ((pid
= fork()) == -1) {
83 fprintf(stderr
, "failed to fork into background");
84 exit(SMF_EXIT_ERR_FATAL
);
88 (void) close(pfds
[1]);
90 if (read(pfds
[0], &status
, sizeof (status
)) == sizeof (status
))
93 if (waitpid(pid
, &status
, 0) == pid
&& WIFEXITED(status
))
94 exit(WEXITSTATUS(status
));
96 exit(SMF_EXIT_ERR_FATAL
);
100 * All child from here on...
103 (void) sigprocmask(SIG_SETMASK
, &oset
, NULL
);
104 (void) close(pfds
[0]);
110 * We are only a daemon if the file descriptor is valid.
113 daemonize_fini(int fd
)
118 (void) write(fd
, &status
, sizeof (status
));
122 if ((fd
= open("/dev/null", O_RDWR
)) >= 0) {
123 (void) fcntl(fd
, F_DUP2FD
, STDIN_FILENO
);
124 (void) fcntl(fd
, F_DUP2FD
, STDOUT_FILENO
);
125 (void) fcntl(fd
, F_DUP2FD
, STDERR_FILENO
);