2 #include "run-command.h"
5 static inline void close_pair(int fd[2])
11 int start_command(struct child_process *cmd)
13 int need_in = !cmd->no_stdin && cmd->in < 0;
14 int need_out = !cmd->stdout_to_stderr && cmd->out < 0;
15 int fdin[2], fdout[2];
19 return -ERR_RUN_COMMAND_PIPE;
25 if (pipe(fdout) < 0) {
28 return -ERR_RUN_COMMAND_PIPE;
40 return -ERR_RUN_COMMAND_FORK;
45 int fd = open("/dev/null", O_RDWR);
56 if (cmd->stdout_to_stderr)
61 } else if (cmd->out > 1) {
67 execv_git_cmd(cmd->argv);
69 execvp(cmd->argv[0], (char *const*) cmd->argv);
71 die("exec %s failed.", cmd->argv[0]);
81 else if (cmd->out > 1)
87 int finish_command(struct child_process *cmd)
96 pid_t waiting = waitpid(cmd->pid, &status, 0);
101 error("waitpid failed (%s)", strerror(errno));
102 return -ERR_RUN_COMMAND_WAITPID;
104 if (waiting != cmd->pid)
105 return -ERR_RUN_COMMAND_WAITPID_WRONG_PID;
106 if (WIFSIGNALED(status))
107 return -ERR_RUN_COMMAND_WAITPID_SIGNAL;
109 if (!WIFEXITED(status))
110 return -ERR_RUN_COMMAND_WAITPID_NOEXIT;
111 code = WEXITSTATUS(status);
118 int run_command(struct child_process *cmd)
120 int code = start_command(cmd);
123 return finish_command(cmd);
126 int run_command_v_opt(const char **argv, int opt)
128 struct child_process cmd;
129 memset(&cmd, 0, sizeof(cmd));
131 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
132 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
133 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
134 return run_command(&cmd);