2 * Copyright (C) 2003-2011 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. */
12 #include "close_on_fork.h"
18 * Spawn a new process and redirect fd 0, 1, and 2.
20 * \param pid Will hold the pid of the created process upon return.
21 * \param file Path of the executable to execute.
22 * \param args The argument array for the command.
23 * \param fds a Pointer to a value-result array.
27 * \sa null(4), pipe(2), dup2(2), fork(2), exec(3).
29 static int para_exec(pid_t
*pid
, const char *file
, char *const *const args
, int *fds
)
31 int ret
, in
[2] = {-1, -1}, out
[2] = {-1, -1}, err
[2] = {-1, -1},
35 if (fds
[0] > 0 && pipe(in
) < 0)
37 if (fds
[1] > 0 && pipe(out
) < 0)
39 if (fds
[2] > 0 && pipe(err
) < 0)
41 if (!fds
[0] || !fds
[1] || !fds
[2]) {
42 ret
= para_open("/dev/null", O_RDWR
, 42);
49 ret
= -ERRNO_TO_PARA_ERROR(errno
);
53 if (!(*pid
)) { /* child */
57 if (in
[0] != STDIN_FILENO
)
58 dup2(in
[0], STDIN_FILENO
);
60 dup2(null
, STDIN_FILENO
);
65 if (out
[1] != STDOUT_FILENO
)
66 dup2(out
[1], STDOUT_FILENO
);
68 dup2(null
, STDOUT_FILENO
);
73 if (err
[1] != STDERR_FILENO
)
74 dup2(err
[1], STDERR_FILENO
);
76 dup2(null
, STDERR_FILENO
);
113 PARA_ERROR_LOG("%s\n", para_strerror(-ret
));
118 * Exec the given command.
120 * \param pid Will hold the pid of the created process upon return.
121 * \param cmdline Holds the command and its arguments, seperated by spaces.
122 * \param fds A pointer to a value-result array.
124 * This function uses fork/exec to create a new process. \a fds must be a
125 * pointer to three integers, corresponding to stdin, stdout and stderr
126 * respectively. It specifies how to deal with fd 0, 1, 2 in the child. The
127 * contents of \a fds are interpreted as follows:
129 * - fd[i] < 0: leave fd \a i alone.
130 * - fd[i] = 0: dup fd \a i to \p /dev/null.
131 * - fd[i] > 0: create a pipe and dup i to one end of that pipe.
132 * Upon return, fd[i] contains the file descriptor of the pipe.
134 * In any case, all unneeded filedescriptors are closed.
138 int para_exec_cmdline_pid(pid_t
*pid
, const char *cmdline
, int *fds
)
143 ret
= create_argv(cmdline
, " \t", &argv
);
146 ret
= para_exec(pid
, argv
[0], argv
, fds
);