VirtualBox

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

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

VbglR3PidFile,VbglR3PidFileClose: Made it build everywhere.

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