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) {
77 execv_git_cmd(cmd->argv);
79 execvp(cmd->argv[0], (char *const*) cmd->argv);
81 die("exec %s failed.", cmd->argv[0]);
91 else if (cmd->out > 1)
97 int finish_command(struct child_process *cmd)
106 pid_t waiting = waitpid(cmd->pid, &status, 0);
111 error("waitpid failed (%s)", strerror(errno));
112 return -ERR_RUN_COMMAND_WAITPID;
114 if (waiting != cmd->pid)
115 return -ERR_RUN_COMMAND_WAITPID_WRONG_PID;
116 if (WIFSIGNALED(status))
117 return -ERR_RUN_COMMAND_WAITPID_SIGNAL;
119 if (!WIFEXITED(status))
120 return -ERR_RUN_COMMAND_WAITPID_NOEXIT;
121 code = WEXITSTATUS(status);
128 int run_command(struct child_process *cmd)
130 int code = start_command(cmd);
133 return finish_command(cmd);
136 int run_command_v_opt(const char **argv, int opt)
138 struct child_process cmd;
139 memset(&cmd, 0, sizeof(cmd));
141 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
142 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
143 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
144 return run_command(&cmd);