VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxGuestLib/VBoxGuestR3LibDaemonize.cpp@ 53421

Last change on this file since 53421 was 53421, checked in by vboxsync, 10 years ago

VBoxGuestLib: add re-spawn option to VbglR3Daemonize().

  • Property svn:eol-style set to native
  • Property svn:keyword set to Id
  • Property svn:keywords set to Id Revision
File size: 9.9 KB
Line 
1/** $Id: VBoxGuestR3LibDaemonize.cpp 53421 2014-12-01 16:00:30Z vboxsync $ */
2/** @file
3 * VBoxGuestR3Lib - Ring-3 Support Library for VirtualBox guest additions, daemonize a process.
4 */
5
6/*
7 * Copyright (C) 2007-2010 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/file.h>
55#include <iprt/process.h>
56#include <iprt/string.h>
57#include "VBGLR3Internal.h"
58
59
60/**
61 * Daemonize the process for running in the background.
62 *
63 * This is supposed to do the same job as the BSD daemon() call.
64 *
65 * @returns 0 on success
66 *
67 * @param fNoChDir Pass false to change working directory to root.
68 * @param fNoClose Pass false to redirect standard file streams to /dev/null.
69 * @param fRespawn Restart the daemonised process after five seconds if it
70 * terminates abnormally.
71 *
72 * @todo Use RTProcDaemonize instead of this.
73 * @todo Implement fRespawn on OS/2.
74 * @todo Make the respawn interval configurable. But not until someone
75 * actually needs that.
76 */
77VBGLR3DECL(int) VbglR3Daemonize(bool fNoChDir, bool fNoClose, bool fRespawn)
78{
79#if defined(RT_OS_OS2)
80 PPIB pPib;
81 PTIB pTib;
82 DosGetInfoBlocks(&pTib, &pPib);
83
84 AssertRelease(!fRespawn);
85 /* Get the full path to the executable. */
86 char szExe[CCHMAXPATH];
87 APIRET rc = DosQueryModuleName(pPib->pib_hmte, sizeof(szExe), szExe);
88 if (rc)
89 return RTErrConvertFromOS2(rc);
90
91 /* calc the length of the command line. */
92 char *pch = pPib->pib_pchcmd;
93 size_t cch0 = strlen(pch);
94 pch += cch0 + 1;
95 size_t cch1 = strlen(pch);
96 pch += cch1 + 1;
97 char *pchArgs;
98 if (cch1 && *pch)
99 {
100 do pch = strchr(pch, '\0') + 1;
101 while (*pch);
102
103 size_t cchTotal = pch - pPib->pib_pchcmd;
104 pchArgs = (char *)alloca(cchTotal + sizeof("--daemonized\0\0"));
105 memcpy(pchArgs, pPib->pib_pchcmd, cchTotal - 1);
106 memcpy(pchArgs + cchTotal - 1, "--daemonized\0\0", sizeof("--daemonized\0\0"));
107 }
108 else
109 {
110 size_t cchTotal = pch - pPib->pib_pchcmd + 1;
111 pchArgs = (char *)alloca(cchTotal + sizeof(" --daemonized "));
112 memcpy(pchArgs, pPib->pib_pchcmd, cch0 + 1);
113 pch = pchArgs + cch0 + 1;
114 memcpy(pch, " --daemonized ", sizeof(" --daemonized ") - 1);
115 pch += sizeof(" --daemonized ") - 1;
116 if (cch1)
117 memcpy(pch, pPib->pib_pchcmd + cch0 + 1, cch1 + 2);
118 else
119 pch[0] = pch[1] = '\0';
120 }
121
122 /* spawn a detach process */
123 char szObj[128];
124 RESULTCODES ResCodes = { 0, 0 };
125 szObj[0] = '\0';
126 rc = DosExecPgm(szObj, sizeof(szObj), EXEC_BACKGROUND, (PCSZ)pchArgs, NULL, &ResCodes, (PCSZ)szExe);
127 if (rc)
128 {
129 /** @todo Change this to some standard log/print error?? */
130 /* VBoxServiceError("DosExecPgm failed with rc=%d and szObj='%s'\n", rc, szObj); */
131 return RTErrConvertFromOS2(rc);
132 }
133 DosExit(EXIT_PROCESS, 0);
134 return VERR_GENERAL_FAILURE;
135
136#elif defined(RT_OS_WINDOWS)
137# error "PORTME"
138
139#else /* the unices */
140 /*
141 * Fork the child process in a new session and quit the parent.
142 *
143 * - fork once and create a new session (setsid). This will detach us
144 * from the controlling tty meaning that we won't receive the SIGHUP
145 * (or any other signal) sent to that session.
146 * - The SIGHUP signal is ignored because the session/parent may throw
147 * us one before we get to the setsid.
148 * - When the parent exit(0) we will become an orphan and re-parented to
149 * the init process.
150 * - Because of the Linux / System V semantics of assigning the controlling
151 * tty automagically when a session leader first opens a tty, we will
152 * fork() once more on Linux to get rid of the session leadership role.
153 */
154
155 struct sigaction OldSigAct;
156 struct sigaction SigAct;
157 RT_ZERO(SigAct);
158 SigAct.sa_handler = SIG_IGN;
159 int rcSigAct = sigaction(SIGHUP, &SigAct, &OldSigAct);
160
161 pid_t pid = fork();
162 if (pid == -1)
163 return RTErrConvertFromErrno(errno);
164 if (pid != 0)
165 exit(0);
166
167 /*
168 * The orphaned child becomes is reparented to the init process.
169 * We create a new session for it (setsid), point the standard
170 * file descriptors to /dev/null, and change to the root directory.
171 */
172 pid_t newpgid = setsid();
173 int SavedErrno = errno;
174 if (rcSigAct != -1)
175 sigaction(SIGHUP, &OldSigAct, NULL);
176 if (newpgid == -1)
177 return RTErrConvertFromErrno(SavedErrno);
178
179 if (!fNoClose)
180 {
181 /* Open stdin(0), stdout(1) and stderr(2) as /dev/null. */
182 int fd = open("/dev/null", O_RDWR);
183 if (fd == -1) /* paranoia */
184 {
185 close(STDIN_FILENO);
186 close(STDOUT_FILENO);
187 close(STDERR_FILENO);
188 fd = open("/dev/null", O_RDWR);
189 }
190 if (fd != -1)
191 {
192 dup2(fd, STDIN_FILENO);
193 dup2(fd, STDOUT_FILENO);
194 dup2(fd, STDERR_FILENO);
195 if (fd > 2)
196 close(fd);
197 }
198 }
199
200 if (!fNoChDir)
201 chdir("/");
202
203 /*
204 * Change the umask - this is non-standard daemon() behavior.
205 */
206 umask(027);
207
208# ifdef RT_OS_LINUX
209 /*
210 * And fork again to lose session leader status (non-standard daemon()
211 * behaviour).
212 */
213 pid = fork();
214 if (pid == -1)
215 return RTErrConvertFromErrno(errno);
216 if (pid != 0)
217 exit(0);
218# endif /* RT_OS_LINUX */
219
220 if (fRespawn)
221 /* We implement re-spawning as a third fork(), with the parent process
222 * monitoring the child and re-starting it after a delay if it exits
223 * abnormally. */
224 for (;;)
225 {
226 int iStatus, rcWait;
227
228 pid = fork();
229 if (pid == -1)
230 return RTErrConvertFromErrno(errno);
231 if (pid == 0)
232 return VINF_SUCCESS;
233 do
234 rcWait = waitpid(pid, &iStatus, 0);
235 while (rcWait == -1 && errno == EINTR);
236 if (rcWait == -1)
237 exit(1);
238 if (WIFEXITED(iStatus) && WEXITSTATUS(iStatus) == 0)
239 exit(0);
240 sleep(5);
241 }
242 return VINF_SUCCESS;
243#endif
244}
245
246
247/**
248 * Creates a PID File and returns the open file descriptor.
249 *
250 * On DOS based system, file sharing (deny write) is used for locking the PID
251 * file.
252 *
253 * On Unix-y systems, an exclusive advisory lock is used for locking the PID
254 * file since the file sharing support is usually missing there.
255 *
256 * This API will overwrite any existing PID Files without a lock on them, on the
257 * assumption that they are stale files which an old process did not properly
258 * clean up.
259 *
260 * @returns IPRT status code.
261 * @param pszPath The path and filename to create the PID File under
262 * @param phFile Where to store the file descriptor of the open (and locked
263 * on Unix-y systems) PID File. On failure, or if another
264 * process owns the PID File, this will be set to NIL_RTFILE.
265 */
266VBGLR3DECL(int) VbglR3PidFile(const char *pszPath, PRTFILE phFile)
267{
268 AssertPtrReturn(pszPath, VERR_INVALID_PARAMETER);
269 AssertPtrReturn(phFile, VERR_INVALID_PARAMETER);
270 *phFile = NIL_RTFILE;
271
272 RTFILE hPidFile;
273 int rc = RTFileOpen(&hPidFile, pszPath,
274 RTFILE_O_READWRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE
275 | (0644 << RTFILE_O_CREATE_MODE_SHIFT));
276 if (RT_SUCCESS(rc))
277 {
278#if !defined(RT_OS_WINDOWS) && !defined(RT_OS_OS2)
279 /** @todo using size 0 for locking means lock all on Posix.
280 * We should adopt this as our convention too, or something
281 * similar. */
282 rc = RTFileLock(hPidFile, RTFILE_LOCK_WRITE, 0, 0);
283 if (RT_FAILURE(rc))
284 RTFileClose(hPidFile);
285 else
286#endif
287 {
288 char szBuf[256];
289 size_t cbPid = RTStrPrintf(szBuf, sizeof(szBuf), "%d\n",
290 RTProcSelf());
291 RTFileWrite(hPidFile, szBuf, cbPid, NULL);
292 *phFile = hPidFile;
293 }
294 }
295 return rc;
296}
297
298
299/**
300 * Close and remove an open PID File.
301 *
302 * @param pszPath The path to the PID File,
303 * @param hFile The handle for the file. NIL_RTFILE is ignored as usual.
304 */
305VBGLR3DECL(void) VbglR3ClosePidFile(const char *pszPath, RTFILE hFile)
306{
307 AssertPtrReturnVoid(pszPath);
308 if (hFile != NIL_RTFILE)
309 {
310#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
311 RTFileWriteAt(hFile, 0, "-1", 2, NULL);
312#else
313 RTFileDelete(pszPath);
314#endif
315 RTFileClose(hFile);
316 }
317}
318
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