Teach run-command about stdout redirection
[git/dscho.git] / run-command.c
blobd20a6ef80c08bcf51ab5e650875ba8994917ca70
1 #include "cache.h"
2 #include "run-command.h"
3 #include "exec_cmd.h"
5 static inline void close_pair(int fd[2])
7 close(fd[0]);
8 close(fd[1]);
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];
17 if (need_in) {
18 if (pipe(fdin) < 0)
19 return -ERR_RUN_COMMAND_PIPE;
20 cmd->in = fdin[1];
21 cmd->close_in = 1;
24 if (need_out) {
25 if (pipe(fdout) < 0) {
26 if (need_in)
27 close_pair(fdin);
28 return -ERR_RUN_COMMAND_PIPE;
30 cmd->out = fdout[0];
31 cmd->close_out = 1;
34 cmd->pid = fork();
35 if (cmd->pid < 0) {
36 if (need_in)
37 close_pair(fdin);
38 if (need_out)
39 close_pair(fdout);
40 return -ERR_RUN_COMMAND_FORK;
43 if (!cmd->pid) {
44 if (cmd->no_stdin) {
45 int fd = open("/dev/null", O_RDWR);
46 dup2(fd, 0);
47 close(fd);
48 } else if (need_in) {
49 dup2(fdin[0], 0);
50 close_pair(fdin);
51 } else if (cmd->in) {
52 dup2(cmd->in, 0);
53 close(cmd->in);
56 if (cmd->stdout_to_stderr)
57 dup2(2, 1);
58 else if (need_out) {
59 dup2(fdout[1], 1);
60 close_pair(fdout);
61 } else if (cmd->out > 1) {
62 dup2(cmd->out, 1);
63 close(cmd->out);
66 if (cmd->git_cmd) {
67 execv_git_cmd(cmd->argv);
68 } else {
69 execvp(cmd->argv[0], (char *const*) cmd->argv);
71 die("exec %s failed.", cmd->argv[0]);
74 if (need_in)
75 close(fdin[0]);
76 else if (cmd->in)
77 close(cmd->in);
79 if (need_out)
80 close(fdout[1]);
81 else if (cmd->out > 1)
82 close(cmd->out);
84 return 0;
87 int finish_command(struct child_process *cmd)
89 if (cmd->close_in)
90 close(cmd->in);
91 if (cmd->close_out)
92 close(cmd->out);
94 for (;;) {
95 int status, code;
96 pid_t waiting = waitpid(cmd->pid, &status, 0);
98 if (waiting < 0) {
99 if (errno == EINTR)
100 continue;
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);
112 if (code)
113 return -code;
114 return 0;
118 int run_command(struct child_process *cmd)
120 int code = start_command(cmd);
121 if (code)
122 return code;
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));
130 cmd.argv = argv;
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);