1 /* Copyright (C) 2003 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file exec.c Helper functions for spawning new processes. */
13 * Spawn a new process and redirect fd 0, 1, and 2.
15 * \param pid Will hold the pid of the created process upon return.
16 * \param file Path of the executable to execute.
17 * \param args The argument array for the command.
18 * \param fds a Pointer to a value-result array.
22 * \sa null(4), pipe(2), dup2(2), fork(2), exec(3).
24 static int para_exec(pid_t
*pid
, const char *file
, char *const *const args
, int *fds
)
26 int ret
, in
[2] = {-1, -1}, out
[2] = {-1, -1}, err
[2] = {-1, -1},
30 if (fds
[0] > 0 && pipe(in
) < 0)
32 if (fds
[1] > 0 && pipe(out
) < 0)
34 if (fds
[2] > 0 && pipe(err
) < 0)
36 if (!fds
[0] || !fds
[1] || !fds
[2]) {
37 ret
= para_open("/dev/null", O_RDWR
, 42);
44 ret
= -ERRNO_TO_PARA_ERROR(errno
);
48 if (!(*pid
)) { /* child */
52 if (in
[0] != STDIN_FILENO
)
53 dup2(in
[0], STDIN_FILENO
);
55 dup2(null
, STDIN_FILENO
);
60 if (out
[1] != STDOUT_FILENO
)
61 dup2(out
[1], STDOUT_FILENO
);
63 dup2(null
, STDOUT_FILENO
);
68 if (err
[1] != STDERR_FILENO
)
69 dup2(err
[1], STDERR_FILENO
);
71 dup2(null
, STDERR_FILENO
);
108 PARA_ERROR_LOG("%s\n", para_strerror(-ret
));
113 * Exec the given command.
115 * \param pid Will hold the pid of the created process upon return.
116 * \param cmdline Holds the command and its arguments, separated by spaces.
117 * \param fds A pointer to a value-result array.
119 * This function uses fork/exec to create a new process. \a fds must be a
120 * pointer to three integers, corresponding to stdin, stdout and stderr
121 * respectively. It specifies how to deal with fd 0, 1, 2 in the child. The
122 * contents of \a fds are interpreted as follows:
124 * - fd[i] < 0: leave fd \a i alone.
125 * - fd[i] = 0: dup fd \a i to \p /dev/null.
126 * - fd[i] > 0: create a pipe and dup i to one end of that pipe.
127 * Upon return, fd[i] contains the file descriptor of the pipe.
129 * In any case, all unneeded file descriptors are closed.
133 int para_exec_cmdline_pid(pid_t
*pid
, const char *cmdline
, int *fds
)
138 ret
= create_argv(cmdline
, " \t", &argv
);
141 ret
= para_exec(pid
, argv
[0], argv
, fds
);