VirtualBox

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

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

iprt/socket.h: RTSocket API.

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