VirtualBox

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

Last change on this file since 26425 was 26425, checked in by vboxsync, 15 years ago

alternative license for VBoxGuestLib is CDDL

  • Property svn:eol-style set to native
  • Property svn:keyword set to Id
  • Property svn:keywords set to Id
File size: 9.1 KB
Line 
1/** $Id: VBoxGuestR3LibDaemonize.cpp 26425 2010-02-11 11:37:08Z vboxsync $ */
2/** @file
3 * VBoxGuestR3Lib - Ring-3 Support Library for VirtualBox guest additions, daemonize a process.
4 */
5
6/*
7 * Copyright (C) 2007-2009 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31
32/*******************************************************************************
33* Header Files *
34*******************************************************************************/
35#if defined(RT_OS_DARWIN)
36# error "PORTME"
37
38#elif defined(RT_OS_OS2)
39# define INCL_BASE
40# define INCL_ERRORS
41# include <os2.h>
42
43# include <iprt/alloca.h>
44# include <iprt/string.h>
45
46#elif defined(RT_OS_WINDOWS)
47# error "PORTME"
48
49#else /* the unices */
50# include <sys/types.h>
51# include <sys/stat.h>
52# include <stdio.h>
53# include <fcntl.h>
54# include <stdlib.h>
55# include <unistd.h>
56# include <signal.h>
57# include <errno.h>
58#endif
59
60#include <iprt/file.h>
61#include <iprt/process.h>
62#include <iprt/string.h>
63#include "VBGLR3Internal.h"
64
65
66/**
67 * Daemonize the process for running in the background.
68 *
69 * This is supposed to do the same job as the BSD daemon() call.
70 *
71 * @returns 0 on success
72 *
73 * @param fNoChDir Pass false to change working directory to root.
74 * @param fNoClose Pass false to redirect standard file streams to /dev/null.
75 */
76VBGLR3DECL(int) VbglR3Daemonize(bool fNoChDir, bool fNoClose)
77{
78#if defined(RT_OS_DARWIN)
79# error "PORTME"
80
81#elif defined(RT_OS_OS2)
82 PPIB pPib;
83 PTIB pTib;
84 DosGetInfoBlocks(&pTib, &pPib);
85
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 sematics 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 chdir("/");
203
204 /*
205 * Change the umask - this is non-standard daemon() behavior.
206 */
207 umask(027);
208
209# ifdef RT_OS_LINUX
210 /*
211 * And fork again to lose session leader status (non-standard daemon()
212 * behaviour).
213 */
214 pid = fork();
215 if (pid == -1)
216 return RTErrConvertFromErrno(errno);
217 if (pid != 0)
218 exit(0);
219# endif /* RT_OS_LINUX */
220
221 return VINF_SUCCESS;
222#endif
223}
224
225
226/**
227 * Creates a PID File and returns the open file descriptor.
228 *
229 * On DOS based system, file sharing (deny write) is used for locking the PID
230 * file.
231 *
232 * On Unix-y systems, an exclusive advisory lock is used for locking the PID
233 * file since the file sharing support is usually missing there.
234 *
235 * This API will overwrite any existing PID Files without a lock on them, on the
236 * assumption that they are stale files which an old process did not properly
237 * clean up.
238 *
239 * @returns IPRT status code.
240 * @param pszPath The path and filename to create the PID File under
241 * @param phFile Where to store the file descriptor of the open (and locked
242 * on Unix-y systems) PID File. On failure, or if another
243 * process owns the PID File, this will be set to NIL_RTFILE.
244 */
245VBGLR3DECL(int) VbglR3PidFile(const char *pszPath, PRTFILE phFile)
246{
247 AssertPtrReturn(pszPath, VERR_INVALID_PARAMETER);
248 AssertPtrReturn(phFile, VERR_INVALID_PARAMETER);
249 *phFile = NIL_RTFILE;
250
251 RTFILE hPidFile;
252 int rc = RTFileOpen(&hPidFile, pszPath,
253 RTFILE_O_READWRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE
254 | (0644 << RTFILE_O_CREATE_MODE_SHIFT));
255 if (RT_SUCCESS(rc))
256 {
257#if !defined(RT_OS_WINDOWS) && !defined(RT_OS_OS2)
258 /** @todo using size 0 for locking means lock all on Posix.
259 * We should adopt this as our convention too, or something
260 * similar. */
261 rc = RTFileLock(hPidFile, RTFILE_LOCK_WRITE, 0, 0);
262 if (RT_FAILURE(rc))
263 RTFileClose(hPidFile);
264 else
265#endif
266 {
267 char szBuf[256];
268 size_t cbPid = RTStrPrintf(szBuf, sizeof(szBuf), "%d\n",
269 RTProcSelf());
270 RTFileWrite(hPidFile, szBuf, cbPid, NULL);
271 *phFile = hPidFile;
272 }
273 }
274 return rc;
275}
276
277
278/**
279 * Close and remove an open PID File.
280 *
281 * @param pszPath The path to the PID File,
282 * @param hFile The handle for the file. NIL_RTFILE is ignored as usual.
283 */
284VBGLR3DECL(void) VbglR3ClosePidFile(const char *pszPath, RTFILE hFile)
285{
286 AssertPtrReturnVoid(pszPath);
287 if (hFile != NIL_RTFILE)
288 {
289#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
290 RTFileWriteAt(hFile, 0, "-1", 2, NULL);
291#else
292 RTFileDelete(pszPath);
293#endif
294 RTFileClose(hFile);
295 }
296}
297
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