Simplify closing two fds at once in run-command.c
[git/kirr.git] / run-command.c
blobbef9775e0807200e07c9780c69e3e1bda0c6c874
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 fdin[2];
16 if (need_in) {
17 if (pipe(fdin) < 0)
18 return -ERR_RUN_COMMAND_PIPE;
19 cmd->in = fdin[1];
20 cmd->close_in = 1;
23 cmd->pid = fork();
24 if (cmd->pid < 0) {
25 if (need_in)
26 close_pair(fdin);
27 return -ERR_RUN_COMMAND_FORK;
30 if (!cmd->pid) {
31 if (cmd->no_stdin) {
32 int fd = open("/dev/null", O_RDWR);
33 dup2(fd, 0);
34 close(fd);
35 } else if (need_in) {
36 dup2(fdin[0], 0);
37 close_pair(fdin);
38 } else if (cmd->in) {
39 dup2(cmd->in, 0);
40 close(cmd->in);
43 if (cmd->stdout_to_stderr)
44 dup2(2, 1);
45 if (cmd->git_cmd) {
46 execv_git_cmd(cmd->argv);
47 } else {
48 execvp(cmd->argv[0], (char *const*) cmd->argv);
50 die("exec %s failed.", cmd->argv[0]);
53 if (need_in)
54 close(fdin[0]);
55 else if (cmd->in)
56 close(cmd->in);
58 return 0;
61 int finish_command(struct child_process *cmd)
63 if (cmd->close_in)
64 close(cmd->in);
66 for (;;) {
67 int status, code;
68 pid_t waiting = waitpid(cmd->pid, &status, 0);
70 if (waiting < 0) {
71 if (errno == EINTR)
72 continue;
73 error("waitpid failed (%s)", strerror(errno));
74 return -ERR_RUN_COMMAND_WAITPID;
76 if (waiting != cmd->pid)
77 return -ERR_RUN_COMMAND_WAITPID_WRONG_PID;
78 if (WIFSIGNALED(status))
79 return -ERR_RUN_COMMAND_WAITPID_SIGNAL;
81 if (!WIFEXITED(status))
82 return -ERR_RUN_COMMAND_WAITPID_NOEXIT;
83 code = WEXITSTATUS(status);
84 if (code)
85 return -code;
86 return 0;
90 int run_command(struct child_process *cmd)
92 int code = start_command(cmd);
93 if (code)
94 return code;
95 return finish_command(cmd);
98 int run_command_v_opt(const char **argv, int opt)
100 struct child_process cmd;
101 memset(&cmd, 0, sizeof(cmd));
102 cmd.argv = argv;
103 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
104 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
105 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
106 return run_command(&cmd);