VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/posix/process-posix.cpp@ 21500

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

process-posix.cpp: papszArgs must not be NULL (see the notes in the execve man page on linux).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 10.4 KB
Line 
1/* $Id: process-posix.cpp 20498 2009-06-12 11:05:46Z vboxsync $ */
2/** @file
3 * IPRT - Process, POSIX.
4 */
5
6/*
7 * Copyright (C) 2006-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 * 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/*******************************************************************************
34* Header Files *
35*******************************************************************************/
36#define LOG_GROUP RTLOGGROUP_PROCESS
37#include <unistd.h>
38#include <stdlib.h>
39#include <errno.h>
40#include <sys/types.h>
41#include <sys/stat.h>
42#include <sys/wait.h>
43#include <fcntl.h>
44#include <signal.h>
45#if defined(RT_OS_LINUX) || defined(RT_OS_OS2)
46# define HAVE_POSIX_SPAWN 1
47#endif
48#ifdef HAVE_POSIX_SPAWN
49# include <spawn.h>
50#endif
51#ifdef RT_OS_DARWIN
52# include <mach-o/dyld.h>
53#endif
54
55#include <iprt/process.h>
56#include <iprt/string.h>
57#include <iprt/assert.h>
58#include <iprt/err.h>
59#include <iprt/env.h>
60#include "internal/process.h"
61
62
63
64RTR3DECL(int) RTProcCreate(const char *pszExec, const char * const *papszArgs, RTENV Env, unsigned fFlags, PRTPROCESS pProcess)
65{
66 int rc;
67
68 /*
69 * Validate input.
70 */
71 AssertPtrReturn(pszExec, VERR_INVALID_POINTER);
72 AssertReturn(*pszExec, VERR_INVALID_PARAMETER);
73 AssertReturn(!(fFlags & ~RTPROC_FLAGS_DAEMONIZE), VERR_INVALID_PARAMETER);
74 AssertReturn(Env != NIL_RTENV, VERR_INVALID_PARAMETER);
75 const char * const *papszEnv = RTEnvGetExecEnvP(Env);
76 AssertPtrReturn(papszEnv, VERR_INVALID_HANDLE);
77 AssertPtrReturn(papszArgs, VERR_INVALID_PARAMETER);
78 /* later: path searching. */
79
80
81 /*
82 * Check for execute access to the file.
83 */
84 if (access(pszExec, X_OK))
85 {
86 rc = RTErrConvertFromErrno(errno);
87 AssertMsgFailed(("'%s' %Rrc!\n", pszExec, rc));
88 return rc;
89 }
90
91#if 0
92 /*
93 * Squeeze gdb --args in front of what's being spawned.
94 */
95 unsigned cArgs = 0;
96 while (papszArgs[cArgs])
97 cArgs++;
98 cArgs += 3;
99 const char **papszArgsTmp = (const char **)alloca(cArgs * sizeof(char *));
100 papszArgsTmp[0] = "/usr/bin/gdb";
101 papszArgsTmp[1] = "--args";
102 papszArgsTmp[2] = pszExec;
103 for (unsigned i = 1; papszArgs[i]; i++)
104 papszArgsTmp[i + 2] = papszArgs[i];
105 papszArgsTmp[cArgs - 1] = NULL;
106 pszExec = papszArgsTmp[0];
107 papszArgs = papszArgsTmp;
108#endif
109
110 /*
111 * Spawn the child.
112 */
113 pid_t pid;
114#ifdef HAVE_POSIX_SPAWN
115 if (!(fFlags & RTPROC_FLAGS_DAEMONIZE))
116 {
117 /** @todo check if it requires any of those two attributes, don't remember atm. */
118 rc = posix_spawn(&pid, pszExec, NULL, NULL, (char * const *)papszArgs,
119 (char * const *)papszEnv);
120 if (!rc)
121 {
122 if (pProcess)
123 *pProcess = pid;
124 return VINF_SUCCESS;
125 }
126 }
127 else
128#endif
129 {
130 pid = fork();
131 if (!pid)
132 {
133 if (fFlags & RTPROC_FLAGS_DAEMONIZE)
134 {
135 rc = RTProcDaemonize(true /* fNoChDir */, false /* fNoClose */, NULL /* pszPidFile */);
136 AssertReleaseMsgFailed(("RTProcDaemonize returns %Rrc errno=%d\n", rc, errno));
137 exit(127);
138 }
139 rc = execve(pszExec, (char * const *)papszArgs, (char * const *)papszEnv);
140 AssertReleaseMsgFailed(("execve returns %d errno=%d\n", rc, errno));
141 exit(127);
142 }
143 if (pid > 0)
144 {
145 if (pProcess)
146 *pProcess = pid;
147 return VINF_SUCCESS;
148 }
149 rc = errno;
150 }
151
152 /* failure, errno value in rc. */
153 AssertMsgFailed(("spawn/exec failed rc=%d\n", rc)); /* this migth be annoying... */
154 return RTErrConvertFromErrno(rc);
155}
156
157
158RTR3DECL(int) RTProcWait(RTPROCESS Process, unsigned fFlags, PRTPROCSTATUS pProcStatus)
159{
160 int rc;
161 do rc = RTProcWaitNoResume(Process, fFlags, pProcStatus);
162 while (rc == VERR_INTERRUPTED);
163 return rc;
164}
165
166RTR3DECL(int) RTProcWaitNoResume(RTPROCESS Process, unsigned fFlags, PRTPROCSTATUS pProcStatus)
167{
168 /*
169 * Validate input.
170 */
171 if (Process <= 0)
172 {
173 AssertMsgFailed(("Invalid Process=%d\n", Process));
174 return VERR_INVALID_PARAMETER;
175 }
176 if (fFlags & ~(RTPROCWAIT_FLAGS_NOBLOCK | RTPROCWAIT_FLAGS_BLOCK))
177 {
178 AssertMsgFailed(("Invalid flags %#x\n", fFlags));
179 return VERR_INVALID_PARAMETER;
180 }
181
182 /*
183 * Performe the wait.
184 */
185 int iStatus = 0;
186 int rc = waitpid(Process, &iStatus, fFlags & RTPROCWAIT_FLAGS_NOBLOCK ? WNOHANG : 0);
187 if (rc > 0)
188 {
189 /*
190 * Fill in the status structure.
191 */
192 if (pProcStatus)
193 {
194 if (WIFEXITED(iStatus))
195 {
196 pProcStatus->enmReason = RTPROCEXITREASON_NORMAL;
197 pProcStatus->iStatus = WEXITSTATUS(iStatus);
198 }
199 else if (WIFSIGNALED(iStatus))
200 {
201 pProcStatus->enmReason = RTPROCEXITREASON_SIGNAL;
202 pProcStatus->iStatus = WTERMSIG(iStatus);
203 }
204 else
205 {
206 Assert(!WIFSTOPPED(iStatus));
207 pProcStatus->enmReason = RTPROCEXITREASON_ABEND;
208 pProcStatus->iStatus = iStatus;
209 }
210 }
211 return VINF_SUCCESS;
212 }
213
214 /*
215 * Child running?
216 */
217 if (!rc)
218 {
219 Assert(fFlags & RTPROCWAIT_FLAGS_NOBLOCK);
220 return VERR_PROCESS_RUNNING;
221 }
222
223 /*
224 * Figure out which error to return.
225 */
226 int iErr = errno;
227 if (iErr == ECHILD)
228 return VERR_PROCESS_NOT_FOUND;
229 return RTErrConvertFromErrno(iErr);
230}
231
232
233RTR3DECL(int) RTProcTerminate(RTPROCESS Process)
234{
235 if (!kill(Process, SIGKILL))
236 return VINF_SUCCESS;
237 return RTErrConvertFromErrno(errno);
238}
239
240
241RTR3DECL(uint64_t) RTProcGetAffinityMask()
242{
243 // @todo
244 return 1;
245}
246
247
248/**
249 * Daemonize the current process, making it a background process. The current
250 * process will exit if daemonizing is successful.
251 *
252 * @returns iprt status code.
253 * @param fNoChDir Pass false to change working directory to "/".
254 * @param fNoClose Pass false to redirect standard file streams to the null device.
255 * @param pszPidfile Path to a file to write the process id of the daemon
256 * process to. Daemonizing will fail if this file already
257 * exists or cannot be written. May be NULL.
258 */
259RTR3DECL(int) RTProcDaemonize(bool fNoChDir, bool fNoClose, const char *pszPidfile)
260{
261 /*
262 * Fork the child process in a new session and quit the parent.
263 *
264 * - fork once and create a new session (setsid). This will detach us
265 * from the controlling tty meaning that we won't receive the SIGHUP
266 * (or any other signal) sent to that session.
267 * - The SIGHUP signal is ignored because the session/parent may throw
268 * us one before we get to the setsid.
269 * - When the parent exit(0) we will become an orphan and re-parented to
270 * the init process.
271 * - Because of the sometimes unexpected semantics of assigning the
272 * controlling tty automagically when a session leader first opens a tty,
273 * we will fork() once more to get rid of the session leadership role.
274 */
275
276 /* We start off by opening the pidfile, so that we can fail straight away
277 * if it already exists. */
278 int fdPidfile = -1;
279 if (pszPidfile != NULL)
280 {
281 /* @note the exclusive create is not guaranteed on all file
282 * systems (e.g. NFSv2) */
283 if ((fdPidfile = open(pszPidfile, O_RDWR | O_CREAT | O_EXCL, 0644)) == -1)
284 return RTErrConvertFromErrno(errno);
285 }
286
287 /* Ignore SIGHUP straight away. */
288 struct sigaction OldSigAct;
289 struct sigaction SigAct;
290 memset(&SigAct, 0, sizeof(SigAct));
291 SigAct.sa_handler = SIG_IGN;
292 int rcSigAct = sigaction(SIGHUP, &SigAct, &OldSigAct);
293
294 /* First fork, to become independent process. */
295 pid_t pid = fork();
296 if (pid == -1)
297 return RTErrConvertFromErrno(errno);
298 if (pid != 0)
299 {
300 /* Parent exits, no longer necessary. Child creates gets reparented
301 * to the init process. */
302 exit(0);
303 }
304
305 /* Create new session, fix up the standard file descriptors and the
306 * current working directory. */
307 pid_t newpgid = setsid();
308 int SavedErrno = errno;
309 if (rcSigAct != -1)
310 sigaction(SIGHUP, &OldSigAct, NULL);
311 if (newpgid == -1)
312 return RTErrConvertFromErrno(SavedErrno);
313
314 if (!fNoClose)
315 {
316 /* Open stdin(0), stdout(1) and stderr(2) as /dev/null. */
317 int fd = open("/dev/null", O_RDWR);
318 if (fd == -1) /* paranoia */
319 {
320 close(STDIN_FILENO);
321 close(STDOUT_FILENO);
322 close(STDERR_FILENO);
323 fd = open("/dev/null", O_RDWR);
324 }
325 if (fd != -1)
326 {
327 dup2(fd, STDIN_FILENO);
328 dup2(fd, STDOUT_FILENO);
329 dup2(fd, STDERR_FILENO);
330 if (fd > 2)
331 close(fd);
332 }
333 }
334
335 if (!fNoChDir)
336 chdir("/");
337
338 /* Second fork to lose session leader status. */
339 pid = fork();
340 if (pid == -1)
341 return RTErrConvertFromErrno(errno);
342 if (pid != 0)
343 {
344 /* Write the pid file, this is done in the parent, before exiting. */
345 if (fdPidfile != -1)
346 {
347 char szBuf[256];
348 size_t cbPid = RTStrPrintf(szBuf, sizeof(szBuf), "%d\n", pid);
349 write(fdPidfile, szBuf, cbPid);
350 close(fdPidfile);
351 }
352 exit(0);
353 }
354
355 return VINF_SUCCESS;
356}
357
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