VirtualBox

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

Last change on this file since 93115 was 93115, checked in by vboxsync, 3 years ago

scm --update-copyright-year

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