VirtualBox

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

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

process-posix.cpp: Drop the old RTProcCreate code.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 15.6 KB
Line 
1/* $Id: process-posix.cpp 26804 2010-02-25 16:26:10Z 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.215389.xyz. 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 "internal/iprt.h"
57
58#include <iprt/assert.h>
59#include <iprt/env.h>
60#include <iprt/err.h>
61#include <iprt/file.h>
62#include <iprt/pipe.h>
63#include <iprt/string.h>
64#include "internal/process.h"
65
66
67
68RTR3DECL(int) RTProcCreate(const char *pszExec, const char * const *papszArgs, RTENV Env, unsigned fFlags, PRTPROCESS pProcess)
69{
70 return RTProcCreateEx(pszExec, papszArgs, Env, fFlags,
71 NULL, NULL, NULL, /* standard handles */
72 NULL /*pszAsUser*/,
73 pProcess);
74}
75
76
77RTR3DECL(int) RTProcCreateEx(const char *pszExec, const char * const *papszArgs, RTENV hEnv, uint32_t fFlags,
78 PCRTHANDLE phStdIn, PCRTHANDLE phStdOut, PCRTHANDLE phStdErr, const char *pszAsUser,
79 PRTPROCESS phProcess)
80{
81 int rc;
82
83 /*
84 * Input validation
85 */
86 AssertPtrReturn(pszExec, VERR_INVALID_POINTER);
87 AssertReturn(*pszExec, VERR_INVALID_PARAMETER);
88 AssertReturn(!(fFlags & ~RTPROC_FLAGS_DAEMONIZE), VERR_INVALID_PARAMETER);
89 AssertReturn(hEnv != NIL_RTENV, VERR_INVALID_PARAMETER);
90 const char * const *papszEnv = RTEnvGetExecEnvP(hEnv);
91 AssertPtrReturn(papszEnv, VERR_INVALID_HANDLE);
92 AssertPtrReturn(papszArgs, VERR_INVALID_PARAMETER);
93 /** @todo search the PATH (add flag for this). */
94 AssertPtrNullReturn(pszAsUser, VERR_INVALID_POINTER);
95
96 /*
97 * Get the file descriptors for the handles we've been passed.
98 */
99 PCRTHANDLE paHandles[3] = { phStdIn, phStdOut, phStdErr };
100 int aStdFds[3] = { -1, -1, -1 };
101 for (int i = 0; i < 3; i++)
102 {
103 if (paHandles[i])
104 {
105 AssertPtrReturn(paHandles[i], VERR_INVALID_POINTER);
106 switch (paHandles[i]->enmType)
107 {
108 case RTHANDLETYPE_FILE:
109 aStdFds[i] = paHandles[i]->u.hFile != NIL_RTFILE
110 ? (int)RTFileToNative(paHandles[i]->u.hFile)
111 : -2 /* close it */;
112 break;
113
114 case RTHANDLETYPE_PIPE:
115 aStdFds[i] = paHandles[i]->u.hPipe != NIL_RTPIPE
116 ? (int)RTPipeToNative(paHandles[i]->u.hPipe)
117 : -2 /* close it */;
118 break;
119
120 case RTHANDLETYPE_SOCKET:
121 aStdFds[i] = paHandles[i]->u.hSocket != NIL_RTSOCKET
122 ? (int)paHandles[i]->u.hSocket //RTPipeToNative(paHandles[i]->u.hPipe)
123 : -2 /* close it */;
124 break;
125
126 default:
127 AssertMsgFailedReturn(("%d: %d\n", i, paHandles[i]->enmType), VERR_INVALID_PARAMETER);
128 }
129 /** @todo check the close-on-execness of these handles? */
130 }
131 }
132
133 for (int i = 0; i < 3; i++)
134 if (aStdFds[i] == i)
135 aStdFds[i] = -1;
136
137 for (int i = 0; i < 3; i++)
138 AssertMsgReturn(aStdFds[i] < 0 || aStdFds[i] > i,
139 ("%i := %i not possible because we're lazy\n", i, aStdFds[i]),
140 VERR_NOT_SUPPORTED);
141
142 /*
143 * Resolve the user id if specified.
144 */
145 uid_t uid = ~(uid_t)0;
146 gid_t gid = ~(gid_t)0;
147 if (pszAsUser)
148 {
149 AssertMsgFailed(("Implement get uid by name lookup\n"));
150 return VERR_NOT_IMPLEMENTED;
151 }
152
153 /*
154 * Check for execute access to the file.
155 */
156 if (access(pszExec, X_OK))
157 {
158 rc = RTErrConvertFromErrno(errno);
159 AssertMsgFailed(("'%s' %Rrc!\n", pszExec, rc));
160 return rc;
161 }
162
163 /*
164 * Spawn the child.
165 *
166 * HACK ALERT! Put the process into a new process group with pgid = pid
167 * to make sure it differs from that of the parent process to ensure that
168 * the IPRT waipit call doesn't race anyone (read XPCOM) doing group wide
169 * waits.
170 */
171 pid_t pid = -1;
172#ifdef HAVE_POSIX_SPAWN
173 if ( !(fFlags & RTPROC_FLAGS_DAEMONIZE)
174 && uid == ~(uid_t)0
175 && gid == ~(gid_t)0
176 )
177 {
178 /* Spawn attributes. */
179 posix_spawnattr_t Attr;
180 rc = posix_spawnattr_init(&Attr);
181 if (!rc)
182 {
183# ifndef RT_OS_OS2 /* We don't need this on OS/2 and I don't recall if it's actually implemented. */
184 rc = posix_spawnattr_setflags(&Attr, POSIX_SPAWN_SETPGROUP);
185 Assert(rc == 0);
186 if (!rc)
187 {
188 rc = posix_spawnattr_setpgroup(&Attr, 0 /* pg == child pid */);
189 Assert(rc == 0);
190 }
191# endif
192
193 /* File changes. */
194 posix_spawn_file_actions_t FileActions;
195 posix_spawn_file_actions_t *pFileActions = NULL;
196 if (aStdFds[0] != -1 || aStdFds[1] != -1 || aStdFds[2] != -1)
197 {
198 rc = posix_spawn_file_actions_init(&FileActions);
199 if (!rc)
200 {
201 pFileActions = &FileActions;
202 for (int i = 0; i < 3; i++)
203 {
204 if (aStdFds[i] == -2)
205 rc = posix_spawn_file_actions_addclose(&FileActions, i);
206 else if (aStdFds[i] >= 0 && aStdFds[i] != i)
207 {
208 rc = posix_spawn_file_actions_adddup2(&FileActions, aStdFds[i], i);
209 if (!rc)
210 rc = posix_spawn_file_actions_addclose(&FileActions, aStdFds[i]);
211 }
212 if (rc)
213 break;
214 }
215 }
216 }
217
218 if (!rc)
219 rc = posix_spawn(&pid, pszExec, NULL, &Attr, (char * const *)papszArgs,
220 (char * const *)papszEnv);
221
222 /* cleanup */
223 int rc2 = posix_spawnattr_destroy(&Attr); Assert(rc2 == 0); NOREF(rc2);
224 if (pFileActions)
225 {
226 rc2 = posix_spawn_file_actions_destroy(pFileActions);
227 Assert(rc2 == 0);
228 }
229
230 /* return on success.*/
231 if (!rc)
232 {
233 if (phProcess)
234 *phProcess = pid;
235 return VINF_SUCCESS;
236 }
237 }
238 }
239 else
240#endif
241 {
242 pid = fork();
243 if (!pid)
244 {
245 setpgid(0, 0); /* see comment above */
246
247 /*
248 * Change group and user if requested.
249 */
250#if 1 /** @todo This needs more work, see suplib/hardening. */
251 if (gid != ~(gid_t)0)
252 {
253 if (setgid(gid))
254 exit(127);
255 }
256
257 if (uid != ~(uid_t)0)
258 {
259 if (setuid(uid))
260 exit(127);
261 }
262#endif
263
264 /*
265 * Apply changes to the standard file descriptor and stuff.
266 */
267 for (int i = 0; i < 3; i++)
268 {
269 if (aStdFds[i] == -2)
270 close(aStdFds[i]);
271 else if (aStdFds[i] >= 0)
272 {
273 if (dup2(aStdFds[i], i) != i)
274 exit(127);
275 close(aStdFds[i]);
276 }
277 }
278
279 /*
280 * Daemonize the process if requested.
281 */
282 if (fFlags & RTPROC_FLAGS_DAEMONIZE)
283 {
284 rc = RTProcDaemonize(true /* fNoChDir */, false /* fNoClose */, NULL /* pszPidFile */);
285 AssertReleaseMsgFailed(("RTProcDaemonize returns %Rrc errno=%d\n", rc, errno));
286 exit(127);
287 }
288
289 /*
290 * Finally, execute the requested program.
291 */
292 rc = execve(pszExec, (char * const *)papszArgs, (char * const *)papszEnv);
293 AssertReleaseMsgFailed(("execve returns %d errno=%d\n", rc, errno));
294 exit(127);
295 }
296 if (pid > 0)
297 {
298 if (phProcess)
299 *phProcess = pid;
300 return VINF_SUCCESS;
301 }
302 rc = errno;
303 }
304
305
306 return VERR_NOT_IMPLEMENTED;
307}
308
309
310RTR3DECL(int) RTProcWait(RTPROCESS Process, unsigned fFlags, PRTPROCSTATUS pProcStatus)
311{
312 int rc;
313 do rc = RTProcWaitNoResume(Process, fFlags, pProcStatus);
314 while (rc == VERR_INTERRUPTED);
315 return rc;
316}
317
318RTR3DECL(int) RTProcWaitNoResume(RTPROCESS Process, unsigned fFlags, PRTPROCSTATUS pProcStatus)
319{
320 /*
321 * Validate input.
322 */
323 if (Process <= 0)
324 {
325 AssertMsgFailed(("Invalid Process=%d\n", Process));
326 return VERR_INVALID_PARAMETER;
327 }
328 if (fFlags & ~(RTPROCWAIT_FLAGS_NOBLOCK | RTPROCWAIT_FLAGS_BLOCK))
329 {
330 AssertMsgFailed(("Invalid flags %#x\n", fFlags));
331 return VERR_INVALID_PARAMETER;
332 }
333
334 /*
335 * Performe the wait.
336 */
337 int iStatus = 0;
338 int rc = waitpid(Process, &iStatus, fFlags & RTPROCWAIT_FLAGS_NOBLOCK ? WNOHANG : 0);
339 if (rc > 0)
340 {
341 /*
342 * Fill in the status structure.
343 */
344 if (pProcStatus)
345 {
346 if (WIFEXITED(iStatus))
347 {
348 pProcStatus->enmReason = RTPROCEXITREASON_NORMAL;
349 pProcStatus->iStatus = WEXITSTATUS(iStatus);
350 }
351 else if (WIFSIGNALED(iStatus))
352 {
353 pProcStatus->enmReason = RTPROCEXITREASON_SIGNAL;
354 pProcStatus->iStatus = WTERMSIG(iStatus);
355 }
356 else
357 {
358 Assert(!WIFSTOPPED(iStatus));
359 pProcStatus->enmReason = RTPROCEXITREASON_ABEND;
360 pProcStatus->iStatus = iStatus;
361 }
362 }
363 return VINF_SUCCESS;
364 }
365
366 /*
367 * Child running?
368 */
369 if (!rc)
370 {
371 Assert(fFlags & RTPROCWAIT_FLAGS_NOBLOCK);
372 return VERR_PROCESS_RUNNING;
373 }
374
375 /*
376 * Figure out which error to return.
377 */
378 int iErr = errno;
379 if (iErr == ECHILD)
380 return VERR_PROCESS_NOT_FOUND;
381 return RTErrConvertFromErrno(iErr);
382}
383
384
385RTR3DECL(int) RTProcTerminate(RTPROCESS Process)
386{
387 if (!kill(Process, SIGKILL))
388 return VINF_SUCCESS;
389 return RTErrConvertFromErrno(errno);
390}
391
392
393RTR3DECL(uint64_t) RTProcGetAffinityMask()
394{
395 // @todo
396 return 1;
397}
398
399
400/**
401 * Daemonize the current process, making it a background process. The current
402 * process will exit if daemonizing is successful.
403 *
404 * @returns iprt status code.
405 * @param fNoChDir Pass false to change working directory to "/".
406 * @param fNoClose Pass false to redirect standard file streams to the null device.
407 * @param pszPidfile Path to a file to write the process id of the daemon
408 * process to. Daemonizing will fail if this file already
409 * exists or cannot be written. May be NULL.
410 */
411RTR3DECL(int) RTProcDaemonize(bool fNoChDir, bool fNoClose, const char *pszPidfile)
412{
413 /*
414 * Fork the child process in a new session and quit the parent.
415 *
416 * - fork once and create a new session (setsid). This will detach us
417 * from the controlling tty meaning that we won't receive the SIGHUP
418 * (or any other signal) sent to that session.
419 * - The SIGHUP signal is ignored because the session/parent may throw
420 * us one before we get to the setsid.
421 * - When the parent exit(0) we will become an orphan and re-parented to
422 * the init process.
423 * - Because of the sometimes unexpected semantics of assigning the
424 * controlling tty automagically when a session leader first opens a tty,
425 * we will fork() once more to get rid of the session leadership role.
426 */
427
428 /* We start off by opening the pidfile, so that we can fail straight away
429 * if it already exists. */
430 int fdPidfile = -1;
431 if (pszPidfile != NULL)
432 {
433 /* @note the exclusive create is not guaranteed on all file
434 * systems (e.g. NFSv2) */
435 if ((fdPidfile = open(pszPidfile, O_RDWR | O_CREAT | O_EXCL, 0644)) == -1)
436 return RTErrConvertFromErrno(errno);
437 }
438
439 /* Ignore SIGHUP straight away. */
440 struct sigaction OldSigAct;
441 struct sigaction SigAct;
442 memset(&SigAct, 0, sizeof(SigAct));
443 SigAct.sa_handler = SIG_IGN;
444 int rcSigAct = sigaction(SIGHUP, &SigAct, &OldSigAct);
445
446 /* First fork, to become independent process. */
447 pid_t pid = fork();
448 if (pid == -1)
449 return RTErrConvertFromErrno(errno);
450 if (pid != 0)
451 {
452 /* Parent exits, no longer necessary. The child gets reparented
453 * to the init process. */
454 exit(0);
455 }
456
457 /* Create new session, fix up the standard file descriptors and the
458 * current working directory. */
459 pid_t newpgid = setsid();
460 int SavedErrno = errno;
461 if (rcSigAct != -1)
462 sigaction(SIGHUP, &OldSigAct, NULL);
463 if (newpgid == -1)
464 return RTErrConvertFromErrno(SavedErrno);
465
466 if (!fNoClose)
467 {
468 /* Open stdin(0), stdout(1) and stderr(2) as /dev/null. */
469 int fd = open("/dev/null", O_RDWR);
470 if (fd == -1) /* paranoia */
471 {
472 close(STDIN_FILENO);
473 close(STDOUT_FILENO);
474 close(STDERR_FILENO);
475 fd = open("/dev/null", O_RDWR);
476 }
477 if (fd != -1)
478 {
479 dup2(fd, STDIN_FILENO);
480 dup2(fd, STDOUT_FILENO);
481 dup2(fd, STDERR_FILENO);
482 if (fd > 2)
483 close(fd);
484 }
485 }
486
487 if (!fNoChDir)
488 int rcChdir = chdir("/");
489
490 /* Second fork to lose session leader status. */
491 pid = fork();
492 if (pid == -1)
493 return RTErrConvertFromErrno(errno);
494
495 if (pid != 0)
496 {
497 /* Write the pid file, this is done in the parent, before exiting. */
498 if (fdPidfile != -1)
499 {
500 char szBuf[256];
501 size_t cbPid = RTStrPrintf(szBuf, sizeof(szBuf), "%d\n", pid);
502 int rcWrite = write(fdPidfile, szBuf, cbPid);
503 close(fdPidfile);
504 }
505 exit(0);
506 }
507
508 return VINF_SUCCESS;
509}
510
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette