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;
30 need_out = !cmd->no_stdout
31 && !cmd->stdout_to_stderr
34 if (pipe(fdout) < 0) {
37 return -ERR_RUN_COMMAND_PIPE;
42 need_err = !cmd->no_stderr && cmd->err < 0;
44 if (pipe(fderr) < 0) {
49 return -ERR_RUN_COMMAND_PIPE;
62 return -ERR_RUN_COMMAND_FORK;
78 else if (cmd->stdout_to_stderr)
83 } else if (cmd->out > 1) {
95 if (cmd->dir && chdir(cmd->dir))
96 die("exec %s: cd to %s failed (%s)", cmd->argv[0],
97 cmd->dir, strerror(errno));
99 for (; *cmd->env; cmd->env++) {
100 if (strchr(*cmd->env, '='))
101 putenv((char*)*cmd->env);
107 execv_git_cmd(cmd->argv);
109 execvp(cmd->argv[0], (char *const*) cmd->argv);
111 die("exec %s failed.", cmd->argv[0]);
121 else if (cmd->out > 1)
130 static int wait_or_whine(pid_t pid)
134 pid_t waiting = waitpid(pid, &status, 0);
139 error("waitpid failed (%s)", strerror(errno));
140 return -ERR_RUN_COMMAND_WAITPID;
143 return -ERR_RUN_COMMAND_WAITPID_WRONG_PID;
144 if (WIFSIGNALED(status))
145 return -ERR_RUN_COMMAND_WAITPID_SIGNAL;
147 if (!WIFEXITED(status))
148 return -ERR_RUN_COMMAND_WAITPID_NOEXIT;
149 code = WEXITSTATUS(status);
156 int finish_command(struct child_process *cmd)
158 return wait_or_whine(cmd->pid);
161 int run_command(struct child_process *cmd)
163 int code = start_command(cmd);
166 return finish_command(cmd);
169 static void prepare_run_command_v_opt(struct child_process *cmd,
173 memset(cmd, 0, sizeof(*cmd));
175 cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
176 cmd->git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
177 cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
180 int run_command_v_opt(const char **argv, int opt)
182 struct child_process cmd;
183 prepare_run_command_v_opt(&cmd, argv, opt);
184 return run_command(&cmd);
187 int run_command_v_opt_cd(const char **argv, int opt, const char *dir)
189 struct child_process cmd;
190 prepare_run_command_v_opt(&cmd, argv, opt);
192 return run_command(&cmd);
195 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
197 struct child_process cmd;
198 prepare_run_command_v_opt(&cmd, argv, opt);
201 return run_command(&cmd);
204 int start_async(struct async *async)
208 if (pipe(pipe_out) < 0)
209 return error("cannot create pipe: %s", strerror(errno));
212 if (async->pid < 0) {
213 error("fork (async) failed: %s", strerror(errno));
214 close_pair(pipe_out);
219 exit(!!async->proc(pipe_out[1], async->data));
221 async->out = pipe_out[0];
226 int finish_async(struct async *async)
230 if (wait_or_whine(async->pid))
231 ret = error("waitpid (async) failed");