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;
21 int fdin[2], fdout[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;
50 return -ERR_RUN_COMMAND_FORK;
66 else if (cmd->stdout_to_stderr)
71 } else if (cmd->out > 1) {
76 if (cmd->dir && chdir(cmd->dir))
77 die("exec %s: cd to %s failed (%s)", cmd->argv[0],
78 cmd->dir, strerror(errno));
80 for (; *cmd->env; cmd->env++) {
81 if (strchr(*cmd->env, '='))
82 putenv((char*)*cmd->env);
88 execv_git_cmd(cmd->argv);
90 execvp(cmd->argv[0], (char *const*) cmd->argv);
92 die("exec %s failed.", cmd->argv[0]);
102 else if (cmd->out > 1)
108 int finish_command(struct child_process *cmd)
117 pid_t waiting = waitpid(cmd->pid, &status, 0);
122 error("waitpid failed (%s)", strerror(errno));
123 return -ERR_RUN_COMMAND_WAITPID;
125 if (waiting != cmd->pid)
126 return -ERR_RUN_COMMAND_WAITPID_WRONG_PID;
127 if (WIFSIGNALED(status))
128 return -ERR_RUN_COMMAND_WAITPID_SIGNAL;
130 if (!WIFEXITED(status))
131 return -ERR_RUN_COMMAND_WAITPID_NOEXIT;
132 code = WEXITSTATUS(status);
139 int run_command(struct child_process *cmd)
141 int code = start_command(cmd);
144 return finish_command(cmd);
147 static void prepare_run_command_v_opt(struct child_process *cmd,
151 memset(cmd, 0, sizeof(*cmd));
153 cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
154 cmd->git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
155 cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
158 int run_command_v_opt(const char **argv, int opt)
160 struct child_process cmd;
161 prepare_run_command_v_opt(&cmd, argv, opt);
162 return run_command(&cmd);
165 int run_command_v_opt_cd(const char **argv, int opt, const char *dir)
167 struct child_process cmd;
168 prepare_run_command_v_opt(&cmd, argv, opt);
170 return run_command(&cmd);
173 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
175 struct child_process cmd;
176 prepare_run_command_v_opt(&cmd, argv, opt);
179 return run_command(&cmd);