VirtualBox

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

Last change on this file since 18320 was 18320, checked in by vboxsync, 16 years ago

Additions/common/VbglR3Lib: separate pidfile and daemonising code. The pidfile code has not yet been tested

  • Property svn:eol-style set to native
  • Property svn:keyword set to Id
  • Property svn:keywords set to Id
File size: 8.3 KB
Line 
1/** $Id: VBoxGuestR3LibDaemonize.cpp 18320 2009-03-26 14:53:12Z vboxsync $ */
2/** @file
3 * VBoxGuestR3Lib - Ring-3 Support Library for VirtualBox guest additions, daemonize a process.
4 */
5
6/*
7 * Copyright (C) 2007 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 * Creates a pidfile and returns the open file descriptor.
218 * On Unix-y systems, this call also places an advisory lock on the open
219 * file. It will overwrite any existing pidfiles without a lock on them,
220 * on the assumption that they are stale files which an old process did not
221 * properly clean up.
222 *
223 * @returns iprt status code
224 * @param pszPath the path and filename to create the pidfile under
225 * @param pFile where to store the file descriptor of the open
226 * (and locked on Unix-y systems) pidfile.
227 * On failure, or if another process owns the pidfile,
228 * this will be set to NIL_RTFILE.
229 */
230VBGLR3DECL(int) VbglR3PidFile(const char *pszPath, PRTFILE pFile)
231{
232 AssertPtrReturn(pszPath, VERR_INVALID_PARAMETER);
233 AssertPtrReturn(pFile, VERR_INVALID_PARAMETER);
234#if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
235 RTFILE hPidFile = NIL_RTFILE;
236 int rc = RTFileOpen(&hPidFile, pszPath,
237 RTFILE_O_READWRITE | RTFILE_O_OPEN_CREATE
238 | (0644 << RTFILE_O_CREATE_MODE_SHIFT));
239 if (RT_SUCCESS(rc))
240 rc = RTFileLock(hPidFile, RTFILE_LOCK_WRITE, 0, ~0);
241 if (RT_SUCCESS(rc))
242 {
243 char szBuf[256];
244 size_t cbPid = RTStrPrintf(szBuf, sizeof(szBuf), "%d\n",
245 RTProcSelf());
246 RTFileWrite(hPidFile, szBuf, cbPid, NULL);
247 }
248 *pFile = hPidFile;
249 return rc;
250#else /* !RT_OS_LINUX and !RT_OS_SOLARIS */
251# error portme
252#endif /* !RT_OS_LINUX and !RT_OS_SOLARIS */
253}
254
255/**
256 * Close and remove an open pidfile.
257 * @param pszPath the path to the pidfile
258 * @param File the open file descriptor
259 */
260VBGLR3DECL(void) VbglR3ClosePidFile(const char *pszPath, RTFILE File)
261{
262 AssertPtrReturnVoid(pszPath);
263 AssertReturnVoid(File != NIL_RTFILE);
264#if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
265 RTFileDelete(pszPath);
266 RTFileClose(File);
267#else /* !RT_OS_LINUX and !RT_OS_SOLARIS */
268# error portme
269#endif /* !RT_OS_LINUX and !RT_OS_SOLARIS */
270}
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