VirtualBox

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

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

Automated rebranding to Oracle copyright/license strings via filemuncher

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