VirtualBox

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

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

re-apply r53640, r53642

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 11.5 KB
Line 
1/* $Id: process-posix.cpp 23919 2009-10-20 17:48:40Z 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 * HACK ALERT! Put the process into a new process group with pgid = pid
114 * to make sure it differs from that of the parent process to ensure that
115 * the IPRT waipit call doesn't race anyone (read XPCOM) doing group wide
116 * waits.
117 */
118 pid_t pid;
119#ifdef HAVE_POSIX_SPAWN
120 if (!(fFlags & RTPROC_FLAGS_DAEMONIZE))
121 {
122 posix_spawnattr_t Attr;
123
124 rc = posix_spawnattr_init(&Attr);
125 if (!rc)
126 {
127# ifndef RT_OS_OS2 /* We don't need this on OS/2 and I don't recall if it's actually implemented. */
128 rc = posix_spawnattr_setflags(&Attr, POSIX_SPAWN_SETPGROUP);
129 Assert(rc == 0);
130 if (!rc)
131 {
132 rc = posix_spawnattr_setpgroup(&Attr, 0 /* pg == child pid */);
133 Assert(rc == 0);
134 }
135# endif
136 if (!rc)
137 {
138 /** @todo check if it requires any mandatory attributes or something, don't
139 * remember atm. */
140 rc = posix_spawn(&pid, pszExec, NULL, &Attr, (char * const *)papszArgs,
141 (char * const *)papszEnv);
142 if (!rc)
143 {
144 int rc2 = posix_spawnattr_destroy(&Attr); Assert(rc2 == 0); NOREF(rc2);
145 if (pProcess)
146 *pProcess = pid;
147 return VINF_SUCCESS;
148 }
149 }
150 int rc2 = posix_spawnattr_destroy(&Attr); Assert(rc2 == 0); NOREF(rc2);
151 }
152 }
153 else
154#endif
155 {
156 pid = fork();
157 if (!pid)
158 {
159 setpgid(0, 0); /* see comment above */
160
161 if (fFlags & RTPROC_FLAGS_DAEMONIZE)
162 {
163 rc = RTProcDaemonize(true /* fNoChDir */, false /* fNoClose */, NULL /* pszPidFile */);
164 AssertReleaseMsgFailed(("RTProcDaemonize returns %Rrc errno=%d\n", rc, errno));
165 exit(127);
166 }
167 rc = execve(pszExec, (char * const *)papszArgs, (char * const *)papszEnv);
168 AssertReleaseMsgFailed(("execve returns %d errno=%d\n", rc, errno));
169 exit(127);
170 }
171 if (pid > 0)
172 {
173 if (pProcess)
174 *pProcess = pid;
175 return VINF_SUCCESS;
176 }
177 rc = errno;
178 }
179
180 /* failure, errno value in rc. */
181 AssertMsgFailed(("spawn/exec failed rc=%d\n", rc)); /* this migth be annoying... */
182 return RTErrConvertFromErrno(rc);
183}
184
185
186RTR3DECL(int) RTProcWait(RTPROCESS Process, unsigned fFlags, PRTPROCSTATUS pProcStatus)
187{
188 int rc;
189 do rc = RTProcWaitNoResume(Process, fFlags, pProcStatus);
190 while (rc == VERR_INTERRUPTED);
191 return rc;
192}
193
194RTR3DECL(int) RTProcWaitNoResume(RTPROCESS Process, unsigned fFlags, PRTPROCSTATUS pProcStatus)
195{
196 /*
197 * Validate input.
198 */
199 if (Process <= 0)
200 {
201 AssertMsgFailed(("Invalid Process=%d\n", Process));
202 return VERR_INVALID_PARAMETER;
203 }
204 if (fFlags & ~(RTPROCWAIT_FLAGS_NOBLOCK | RTPROCWAIT_FLAGS_BLOCK))
205 {
206 AssertMsgFailed(("Invalid flags %#x\n", fFlags));
207 return VERR_INVALID_PARAMETER;
208 }
209
210 /*
211 * Performe the wait.
212 */
213 int iStatus = 0;
214 int rc = waitpid(Process, &iStatus, fFlags & RTPROCWAIT_FLAGS_NOBLOCK ? WNOHANG : 0);
215 if (rc > 0)
216 {
217 /*
218 * Fill in the status structure.
219 */
220 if (pProcStatus)
221 {
222 if (WIFEXITED(iStatus))
223 {
224 pProcStatus->enmReason = RTPROCEXITREASON_NORMAL;
225 pProcStatus->iStatus = WEXITSTATUS(iStatus);
226 }
227 else if (WIFSIGNALED(iStatus))
228 {
229 pProcStatus->enmReason = RTPROCEXITREASON_SIGNAL;
230 pProcStatus->iStatus = WTERMSIG(iStatus);
231 }
232 else
233 {
234 Assert(!WIFSTOPPED(iStatus));
235 pProcStatus->enmReason = RTPROCEXITREASON_ABEND;
236 pProcStatus->iStatus = iStatus;
237 }
238 }
239 return VINF_SUCCESS;
240 }
241
242 /*
243 * Child running?
244 */
245 if (!rc)
246 {
247 Assert(fFlags & RTPROCWAIT_FLAGS_NOBLOCK);
248 return VERR_PROCESS_RUNNING;
249 }
250
251 /*
252 * Figure out which error to return.
253 */
254 int iErr = errno;
255 if (iErr == ECHILD)
256 return VERR_PROCESS_NOT_FOUND;
257 return RTErrConvertFromErrno(iErr);
258}
259
260
261RTR3DECL(int) RTProcTerminate(RTPROCESS Process)
262{
263 if (!kill(Process, SIGKILL))
264 return VINF_SUCCESS;
265 return RTErrConvertFromErrno(errno);
266}
267
268
269RTR3DECL(uint64_t) RTProcGetAffinityMask()
270{
271 // @todo
272 return 1;
273}
274
275
276/**
277 * Daemonize the current process, making it a background process. The current
278 * process will exit if daemonizing is successful.
279 *
280 * @returns iprt status code.
281 * @param fNoChDir Pass false to change working directory to "/".
282 * @param fNoClose Pass false to redirect standard file streams to the null device.
283 * @param pszPidfile Path to a file to write the process id of the daemon
284 * process to. Daemonizing will fail if this file already
285 * exists or cannot be written. May be NULL.
286 */
287RTR3DECL(int) RTProcDaemonize(bool fNoChDir, bool fNoClose, const char *pszPidfile)
288{
289 /*
290 * Fork the child process in a new session and quit the parent.
291 *
292 * - fork once and create a new session (setsid). This will detach us
293 * from the controlling tty meaning that we won't receive the SIGHUP
294 * (or any other signal) sent to that session.
295 * - The SIGHUP signal is ignored because the session/parent may throw
296 * us one before we get to the setsid.
297 * - When the parent exit(0) we will become an orphan and re-parented to
298 * the init process.
299 * - Because of the sometimes unexpected semantics of assigning the
300 * controlling tty automagically when a session leader first opens a tty,
301 * we will fork() once more to get rid of the session leadership role.
302 */
303
304 /* We start off by opening the pidfile, so that we can fail straight away
305 * if it already exists. */
306 int fdPidfile = -1;
307 if (pszPidfile != NULL)
308 {
309 /* @note the exclusive create is not guaranteed on all file
310 * systems (e.g. NFSv2) */
311 if ((fdPidfile = open(pszPidfile, O_RDWR | O_CREAT | O_EXCL, 0644)) == -1)
312 return RTErrConvertFromErrno(errno);
313 }
314
315 /* Ignore SIGHUP straight away. */
316 struct sigaction OldSigAct;
317 struct sigaction SigAct;
318 memset(&SigAct, 0, sizeof(SigAct));
319 SigAct.sa_handler = SIG_IGN;
320 int rcSigAct = sigaction(SIGHUP, &SigAct, &OldSigAct);
321
322 /* First fork, to become independent process. */
323 pid_t pid = fork();
324 if (pid == -1)
325 return RTErrConvertFromErrno(errno);
326 if (pid != 0)
327 {
328 /* Parent exits, no longer necessary. Child creates gets reparented
329 * to the init process. */
330 exit(0);
331 }
332
333 /* Create new session, fix up the standard file descriptors and the
334 * current working directory. */
335 pid_t newpgid = setsid();
336 int SavedErrno = errno;
337 if (rcSigAct != -1)
338 sigaction(SIGHUP, &OldSigAct, NULL);
339 if (newpgid == -1)
340 return RTErrConvertFromErrno(SavedErrno);
341
342 if (!fNoClose)
343 {
344 /* Open stdin(0), stdout(1) and stderr(2) as /dev/null. */
345 int fd = open("/dev/null", O_RDWR);
346 if (fd == -1) /* paranoia */
347 {
348 close(STDIN_FILENO);
349 close(STDOUT_FILENO);
350 close(STDERR_FILENO);
351 fd = open("/dev/null", O_RDWR);
352 }
353 if (fd != -1)
354 {
355 dup2(fd, STDIN_FILENO);
356 dup2(fd, STDOUT_FILENO);
357 dup2(fd, STDERR_FILENO);
358 if (fd > 2)
359 close(fd);
360 }
361 }
362
363 if (!fNoChDir)
364 chdir("/");
365
366 /* Second fork to lose session leader status. */
367 pid = fork();
368 if (pid == -1)
369 return RTErrConvertFromErrno(errno);
370 if (pid != 0)
371 {
372 /* Write the pid file, this is done in the parent, before exiting. */
373 if (fdPidfile != -1)
374 {
375 char szBuf[256];
376 size_t cbPid = RTStrPrintf(szBuf, sizeof(szBuf), "%d\n", pid);
377 write(fdPidfile, szBuf, cbPid);
378 close(fdPidfile);
379 }
380 exit(0);
381 }
382
383 return VINF_SUCCESS;
384}
385
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