VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxGuest/lib/VBoxGuestR3LibDaemonize.cpp@ 96407

Last change on this file since 96407 was 96407, checked in by vboxsync, 2 years ago

scm copyright and license note update

  • Property svn:eol-style set to native
  • Property svn:keyword set to Id
  • Property svn:keywords set to Id Revision
File size: 8.4 KB
Line 
1/** $Id: VBoxGuestR3LibDaemonize.cpp 96407 2022-08-22 17:43:14Z vboxsync $ */
2/** @file
3 * VBoxGuestR3Lib - Ring-3 Support Library for VirtualBox guest additions, daemonize a process.
4 */
5
6/*
7 * Copyright (C) 2007-2022 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#if defined(RT_OS_OS2)
42# define INCL_BASE
43# define INCL_ERRORS
44# include <os2.h>
45
46# include <iprt/alloca.h>
47# include <iprt/string.h>
48
49#elif defined(RT_OS_WINDOWS)
50# error "PORTME"
51
52#else /* the unices */
53# include <sys/types.h>
54# include <sys/stat.h>
55# include <sys/wait.h>
56# include <stdio.h>
57# include <fcntl.h>
58# include <stdlib.h>
59# include <unistd.h>
60# include <signal.h>
61# include <errno.h>
62#endif
63
64#include <iprt/process.h>
65#include <iprt/string.h>
66#include "VBoxGuestR3LibInternal.h"
67
68
69/**
70 * Daemonize the process for running in the background.
71 *
72 * This is supposed to do the same job as the BSD daemon() call.
73 *
74 * @returns 0 on success
75 *
76 * @param fNoChDir Pass false to change working directory to root.
77 * @param fNoClose Pass false to redirect standard file streams to /dev/null.
78 * @param fRespawn Restart the daemonised process after five seconds if it
79 * terminates abnormally.
80 * @param pcRespawn Where to store a count of how often we have respawned,
81 * intended for avoiding error spamming. Optional.
82 *
83 * @todo Use RTProcDaemonize instead of this.
84 * @todo Implement fRespawn on OS/2.
85 * @todo Make the respawn interval configurable. But not until someone
86 * actually needs that.
87 */
88VBGLR3DECL(int) VbglR3Daemonize(bool fNoChDir, bool fNoClose, bool fRespawn, unsigned *pcRespawn)
89{
90#if defined(RT_OS_OS2)
91 PPIB pPib;
92 PTIB pTib;
93 DosGetInfoBlocks(&pTib, &pPib);
94
95 AssertRelease(!fRespawn);
96 /* Get the full path to the executable. */
97 char szExe[CCHMAXPATH];
98 APIRET rc = DosQueryModuleName(pPib->pib_hmte, sizeof(szExe), szExe);
99 if (rc)
100 return RTErrConvertFromOS2(rc);
101
102 /* calc the length of the command line. */
103 char *pch = pPib->pib_pchcmd;
104 size_t cch0 = strlen(pch);
105 pch += cch0 + 1;
106 size_t cch1 = strlen(pch);
107 pch += cch1 + 1;
108 char *pchArgs;
109 if (cch1 && *pch)
110 {
111 do pch = strchr(pch, '\0') + 1;
112 while (*pch);
113
114 size_t cchTotal = pch - pPib->pib_pchcmd;
115 pchArgs = (char *)alloca(cchTotal + sizeof("--daemonized\0\0"));
116 memcpy(pchArgs, pPib->pib_pchcmd, cchTotal - 1);
117 memcpy(pchArgs + cchTotal - 1, "--daemonized\0\0", sizeof("--daemonized\0\0"));
118 }
119 else
120 {
121 size_t cchTotal = pch - pPib->pib_pchcmd + 1;
122 pchArgs = (char *)alloca(cchTotal + sizeof(" --daemonized "));
123 memcpy(pchArgs, pPib->pib_pchcmd, cch0 + 1);
124 pch = pchArgs + cch0 + 1;
125 memcpy(pch, " --daemonized ", sizeof(" --daemonized ") - 1);
126 pch += sizeof(" --daemonized ") - 1;
127 if (cch1)
128 memcpy(pch, pPib->pib_pchcmd + cch0 + 1, cch1 + 2);
129 else
130 pch[0] = pch[1] = '\0';
131 }
132
133 /* spawn a detach process */
134 char szObj[128];
135 RESULTCODES ResCodes = { 0, 0 };
136 szObj[0] = '\0';
137 rc = DosExecPgm(szObj, sizeof(szObj), EXEC_BACKGROUND, (PCSZ)pchArgs, NULL, &ResCodes, (PCSZ)szExe);
138 if (rc)
139 {
140 /** @todo Change this to some standard log/print error?? */
141 /* VBoxServiceError("DosExecPgm failed with rc=%d and szObj='%s'\n", rc, szObj); */
142 return RTErrConvertFromOS2(rc);
143 }
144 DosExit(EXIT_PROCESS, 0);
145 return VERR_GENERAL_FAILURE;
146
147#elif defined(RT_OS_WINDOWS)
148# error "PORTME"
149
150#else /* the unices */
151 /*
152 * Fork the child process in a new session and quit the parent.
153 *
154 * - fork once and create a new session (setsid). This will detach us
155 * from the controlling tty meaning that we won't receive the SIGHUP
156 * (or any other signal) sent to that session.
157 * - The SIGHUP signal is ignored because the session/parent may throw
158 * us one before we get to the setsid.
159 * - When the parent exit(0) we will become an orphan and re-parented to
160 * the init process.
161 * - Because of the Linux / System V semantics of assigning the controlling
162 * tty automagically when a session leader first opens a tty, we will
163 * fork() once more on Linux to get rid of the session leadership role.
164 */
165
166 struct sigaction OldSigAct;
167 struct sigaction SigAct;
168 RT_ZERO(SigAct);
169 SigAct.sa_handler = SIG_IGN;
170 int rcSigAct = sigaction(SIGHUP, &SigAct, &OldSigAct);
171
172 pid_t pid = fork();
173 if (pid == -1)
174 return RTErrConvertFromErrno(errno);
175 if (pid != 0)
176 exit(0);
177
178 /*
179 * The orphaned child becomes is reparented to the init process.
180 * We create a new session for it (setsid), point the standard
181 * file descriptors to /dev/null, and change to the root directory.
182 */
183 pid_t newpgid = setsid();
184 int SavedErrno = errno;
185 if (rcSigAct != -1)
186 sigaction(SIGHUP, &OldSigAct, NULL);
187 if (newpgid == -1)
188 return RTErrConvertFromErrno(SavedErrno);
189
190 if (!fNoClose)
191 {
192 /* Open stdin(0), stdout(1) and stderr(2) as /dev/null. */
193 int fd = open("/dev/null", O_RDWR);
194 if (fd == -1) /* paranoia */
195 {
196 close(STDIN_FILENO);
197 close(STDOUT_FILENO);
198 close(STDERR_FILENO);
199 fd = open("/dev/null", O_RDWR);
200 }
201 if (fd != -1)
202 {
203 dup2(fd, STDIN_FILENO);
204 dup2(fd, STDOUT_FILENO);
205 dup2(fd, STDERR_FILENO);
206 if (fd > 2)
207 close(fd);
208 }
209 }
210
211 if (!fNoChDir)
212 {
213 int rcShutUpGcc = chdir("/");
214 RT_NOREF_PV(rcShutUpGcc);
215 }
216
217 /*
218 * Change the umask - this is non-standard daemon() behavior.
219 */
220 umask(027);
221
222# ifdef RT_OS_LINUX
223 /*
224 * And fork again to lose session leader status (non-standard daemon()
225 * behaviour).
226 */
227 pid = fork();
228 if (pid == -1)
229 return RTErrConvertFromErrno(errno);
230 if (pid != 0)
231 exit(0);
232# endif /* RT_OS_LINUX */
233
234 if (fRespawn)
235 {
236 /* We implement re-spawning as a third fork(), with the parent process
237 * monitoring the child and re-starting it after a delay if it exits
238 * abnormally. */
239 unsigned cRespawn = 0;
240 for (;;)
241 {
242 int iStatus, rcWait;
243
244 if (pcRespawn != NULL)
245 *pcRespawn = cRespawn;
246 pid = fork();
247 if (pid == -1)
248 return RTErrConvertFromErrno(errno);
249 if (pid == 0)
250 return VINF_SUCCESS;
251 do
252 rcWait = waitpid(pid, &iStatus, 0);
253 while (rcWait == -1 && errno == EINTR);
254 if (rcWait == -1)
255 exit(1);
256 if (WIFEXITED(iStatus) && WEXITSTATUS(iStatus) == 0)
257 exit(0);
258 sleep(5);
259 ++cRespawn;
260 }
261 }
262 return VINF_SUCCESS;
263#endif
264}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette