6 #include <linux/string.h>
9 #include "subcmd-util.h"
10 #include "run-command.h"
13 #define STRERR_BUFSIZE 128
15 static inline void close_pair(int fd
[2])
21 static inline void dup_devnull(int to
)
23 int fd
= open("/dev/null", O_RDWR
);
28 int start_command(struct child_process
*cmd
)
30 int need_in
, need_out
, need_err
;
31 int fdin
[2], fdout
[2], fderr
[2];
32 char sbuf
[STRERR_BUFSIZE
];
35 * In case of errors we must keep the promise to close FDs
36 * that have been passed in via ->in and ->out.
39 need_in
= !cmd
->no_stdin
&& cmd
->in
< 0;
44 return -ERR_RUN_COMMAND_PIPE
;
49 need_out
= !cmd
->no_stdout
50 && !cmd
->stdout_to_stderr
53 if (pipe(fdout
) < 0) {
58 return -ERR_RUN_COMMAND_PIPE
;
63 need_err
= !cmd
->no_stderr
&& cmd
->err
< 0;
65 if (pipe(fderr
) < 0) {
74 return -ERR_RUN_COMMAND_PIPE
;
101 else if (cmd
->stdout_to_stderr
)
106 } else if (cmd
->out
> 1) {
111 if (cmd
->dir
&& chdir(cmd
->dir
))
112 die("exec %s: cd to %s failed (%s)", cmd
->argv
[0],
113 cmd
->dir
, str_error_r(errno
, sbuf
, sizeof(sbuf
)));
115 for (; *cmd
->env
; cmd
->env
++) {
116 if (strchr(*cmd
->env
, '='))
117 putenv((char*)*cmd
->env
);
125 execv_cmd(cmd
->argv
);
127 execvp(cmd
->argv
[0], (char *const*) cmd
->argv
);
144 return err
== ENOENT
?
145 -ERR_RUN_COMMAND_EXEC
:
146 -ERR_RUN_COMMAND_FORK
;
165 static int wait_or_whine(pid_t pid
)
167 char sbuf
[STRERR_BUFSIZE
];
171 pid_t waiting
= waitpid(pid
, &status
, 0);
176 fprintf(stderr
, " Error: waitpid failed (%s)",
177 str_error_r(errno
, sbuf
, sizeof(sbuf
)));
178 return -ERR_RUN_COMMAND_WAITPID
;
181 return -ERR_RUN_COMMAND_WAITPID_WRONG_PID
;
182 if (WIFSIGNALED(status
))
183 return -ERR_RUN_COMMAND_WAITPID_SIGNAL
;
185 if (!WIFEXITED(status
))
186 return -ERR_RUN_COMMAND_WAITPID_NOEXIT
;
187 code
= WEXITSTATUS(status
);
190 return -ERR_RUN_COMMAND_EXEC
;
199 int finish_command(struct child_process
*cmd
)
201 return wait_or_whine(cmd
->pid
);
204 int run_command(struct child_process
*cmd
)
206 int code
= start_command(cmd
);
209 return finish_command(cmd
);
212 static void prepare_run_command_v_opt(struct child_process
*cmd
,
216 memset(cmd
, 0, sizeof(*cmd
));
218 cmd
->no_stdin
= opt
& RUN_COMMAND_NO_STDIN
? 1 : 0;
219 cmd
->exec_cmd
= opt
& RUN_EXEC_CMD
? 1 : 0;
220 cmd
->stdout_to_stderr
= opt
& RUN_COMMAND_STDOUT_TO_STDERR
? 1 : 0;
223 int run_command_v_opt(const char **argv
, int opt
)
225 struct child_process cmd
;
226 prepare_run_command_v_opt(&cmd
, argv
, opt
);
227 return run_command(&cmd
);