gitweb: Empty patch for merge means trivial merge, not no differences
[git/peff.git] / run-command.c
blobeff523e191b35385895f6b077fc76c7c21819012
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 static inline void dup_devnull(int to)
13 int fd = open("/dev/null", O_RDWR);
14 dup2(fd, to);
15 close(fd);
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;
24 if (need_in) {
25 if (pipe(fdin) < 0)
26 return -ERR_RUN_COMMAND_PIPE;
27 cmd->in = fdin[1];
28 cmd->close_in = 1;
31 need_out = !cmd->no_stdout
32 && !cmd->stdout_to_stderr
33 && cmd->out < 0;
34 if (need_out) {
35 if (pipe(fdout) < 0) {
36 if (need_in)
37 close_pair(fdin);
38 return -ERR_RUN_COMMAND_PIPE;
40 cmd->out = fdout[0];
41 cmd->close_out = 1;
44 cmd->pid = fork();
45 if (cmd->pid < 0) {
46 if (need_in)
47 close_pair(fdin);
48 if (need_out)
49 close_pair(fdout);
50 return -ERR_RUN_COMMAND_FORK;
53 if (!cmd->pid) {
54 if (cmd->no_stdin)
55 dup_devnull(0);
56 else if (need_in) {
57 dup2(fdin[0], 0);
58 close_pair(fdin);
59 } else if (cmd->in) {
60 dup2(cmd->in, 0);
61 close(cmd->in);
64 if (cmd->no_stdout)
65 dup_devnull(1);
66 else if (cmd->stdout_to_stderr)
67 dup2(2, 1);
68 else if (need_out) {
69 dup2(fdout[1], 1);
70 close_pair(fdout);
71 } else if (cmd->out > 1) {
72 dup2(cmd->out, 1);
73 close(cmd->out);
76 if (cmd->git_cmd) {
77 execv_git_cmd(cmd->argv);
78 } else {
79 execvp(cmd->argv[0], (char *const*) cmd->argv);
81 die("exec %s failed.", cmd->argv[0]);
84 if (need_in)
85 close(fdin[0]);
86 else if (cmd->in)
87 close(cmd->in);
89 if (need_out)
90 close(fdout[1]);
91 else if (cmd->out > 1)
92 close(cmd->out);
94 return 0;
97 int finish_command(struct child_process *cmd)
99 if (cmd->close_in)
100 close(cmd->in);
101 if (cmd->close_out)
102 close(cmd->out);
104 for (;;) {
105 int status, code;
106 pid_t waiting = waitpid(cmd->pid, &status, 0);
108 if (waiting < 0) {
109 if (errno == EINTR)
110 continue;
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);
122 if (code)
123 return -code;
124 return 0;
128 int run_command(struct child_process *cmd)
130 int code = start_command(cmd);
131 if (code)
132 return code;
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));
140 cmd.argv = argv;
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);