2 #include "run-command.h"
5 static inline void close_pair(int fd[2])
11 static inline void dup_devnull(int to)
13 int fd = open("/dev/null", O_RDWR);
18 int start_command(struct child_process *cmd)
20 int need_in, need_out, need_err;
21 int fdin[2], fdout[2], fderr[2];
23 need_in = !cmd->no_stdin && cmd->in < 0;
26 return -ERR_RUN_COMMAND_PIPE;
31 need_out = !cmd->no_stdout
32 && !cmd->stdout_to_stderr
35 if (pipe(fdout) < 0) {
38 return -ERR_RUN_COMMAND_PIPE;
44 need_err = !cmd->no_stderr && cmd->err < 0;
46 if (pipe(fderr) < 0) {
51 return -ERR_RUN_COMMAND_PIPE;
64 return -ERR_RUN_COMMAND_FORK;
80 else if (cmd->stdout_to_stderr)
85 } else if (cmd->out > 1) {
97 if (cmd->dir && chdir(cmd->dir))
98 die("exec %s: cd to %s failed (%s)", cmd->argv[0],
99 cmd->dir, strerror(errno));
101 for (; *cmd->env; cmd->env++) {
102 if (strchr(*cmd->env, '='))
103 putenv((char*)*cmd->env);
109 execv_git_cmd(cmd->argv);
111 execvp(cmd->argv[0], (char *const*) cmd->argv);
113 die("exec %s failed.", cmd->argv[0]);
123 else if (cmd->out > 1)
132 static int wait_or_whine(pid_t pid)
136 pid_t waiting = waitpid(pid, &status, 0);
141 error("waitpid failed (%s)", strerror(errno));
142 return -ERR_RUN_COMMAND_WAITPID;
145 return -ERR_RUN_COMMAND_WAITPID_WRONG_PID;
146 if (WIFSIGNALED(status))
147 return -ERR_RUN_COMMAND_WAITPID_SIGNAL;
149 if (!WIFEXITED(status))
150 return -ERR_RUN_COMMAND_WAITPID_NOEXIT;
151 code = WEXITSTATUS(status);
158 int finish_command(struct child_process *cmd)
164 return wait_or_whine(cmd->pid);
167 int run_command(struct child_process *cmd)
169 int code = start_command(cmd);
172 return finish_command(cmd);
175 static void prepare_run_command_v_opt(struct child_process *cmd,
179 memset(cmd, 0, sizeof(*cmd));
181 cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
182 cmd->git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
183 cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
186 int run_command_v_opt(const char **argv, int opt)
188 struct child_process cmd;
189 prepare_run_command_v_opt(&cmd, argv, opt);
190 return run_command(&cmd);
193 int run_command_v_opt_cd(const char **argv, int opt, const char *dir)
195 struct child_process cmd;
196 prepare_run_command_v_opt(&cmd, argv, opt);
198 return run_command(&cmd);
201 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
203 struct child_process cmd;
204 prepare_run_command_v_opt(&cmd, argv, opt);
207 return run_command(&cmd);
210 int start_async(struct async *async)
214 if (pipe(pipe_out) < 0)
215 return error("cannot create pipe: %s", strerror(errno));
218 if (async->pid < 0) {
219 error("fork (async) failed: %s", strerror(errno));
220 close_pair(pipe_out);
225 exit(!!async->proc(pipe_out[1], async->data));
227 async->out = pipe_out[0];
232 int finish_async(struct async *async)
236 if (wait_or_whine(async->pid))
237 ret = error("waitpid (async) failed");