0886a0b772f504e6009ae898f03858bb18ad0cf3
2 * Copyright (C) 2003-2006 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file exec.c helper functions for spawning new processes */
9 #include "close_on_fork.h"
14 * spawn a new process and redirect fd 0, 1, and 2
16 * \param pid will hold the pid of the created process upon return
17 * \param file path of the executable to execute
18 * \param args the argument array for the command
19 * \param fds a pointer to a value-result array
21 * \return Negative on errors, positive on success.
23 * \sa null(4), pipe(2), dup2(2), fork(2), exec(3)
25 static int para_exec(pid_t
*pid
, const char *file
, char *const *const args
, int *fds
)
27 int ret
, in
[2] = {-1, -1}, out
[2] = {-1, -1}, err
[2] = {-1, -1},
31 if (fds
[0] > 0 && pipe(in
) < 0)
33 if (fds
[1] > 0 && pipe(out
) < 0)
35 if (fds
[2] > 0 && pipe(err
) < 0)
37 if (!fds
[0] || !fds
[1] || !fds
[2]) {
39 null
= open("/dev/null", O_RDONLY
);
43 if ((*pid
= fork()) < 0)
45 if (!(*pid
)) { /* child */
46 close_listed_fds(); /* close unneeded fds */
50 if (in
[0] != STDIN_FILENO
)
51 dup2(in
[0], STDIN_FILENO
);
53 dup2(null
, STDIN_FILENO
);
58 if (out
[1] != STDOUT_FILENO
)
59 dup2(out
[1], STDOUT_FILENO
);
61 dup2(null
, STDOUT_FILENO
);
66 if (err
[1] != STDERR_FILENO
)
67 dup2(err
[1], STDERR_FILENO
);
69 dup2(null
, STDERR_FILENO
);
111 * exec the given command
113 * \param pid will hold the pid of the created process upon return
114 * \param cmdline holds the command and its arguments, seperated by spaces
115 * \param fds a pointer to a value-result array
117 * This function uses fork/exec to create a new process. \a fds must be a
118 * pointer to three integers, corresponding to stdin, stdout and stderr
119 * respectively. It specifies how to deal with fd 0, 1, 2 in the child. The
120 * contents of \a fds are interpreted as follows:
122 * - fd[i] < 0: leave fd \a i alone
123 * - fd[i] = 0: dup fd \a i to /dev/null
124 * - fd[i] > 0: create a pipe and dup i to one end of that pipe.
125 * Upon return, fd[i] contains the file descriptor of the pipe.
127 * In any case, all unneeded filedescriptors are closed.
129 * \return positive on success, negative on errors
131 int para_exec_cmdline_pid(pid_t
*pid
, const char *cmdline
, int *fds
)
135 char *tmp
= para_strdup(cmdline
);
139 argc
= split_args(tmp
, &argv
, " \t");
140 ret
= para_exec(pid
, argv
[0], argv
, fds
);