2 #include "run-command.h"
4 #include "spawn-pipe.h"
6 static inline void close_pair(int fd
[2])
12 int start_command(struct child_process
*cmd
)
14 int need_in
, need_out
;
15 int fdin
[2] = { -1, -1 };
16 int fdout
[2] = { -1, -1 };
17 const char **env
= (const char **) environ
;
19 need_in
= !cmd
->no_stdin
&& cmd
->in
< 0;
22 return -ERR_RUN_COMMAND_PIPE
;
27 need_out
= !cmd
->no_stdout
28 && !cmd
->stdout_to_stderr
31 if (pipe(fdout
) < 0) {
34 return -ERR_RUN_COMMAND_PIPE
;
42 fdin
[0] = open("/dev/null", O_RDWR
);
50 fdout
[1] = open("/dev/null", O_RDWR
);
51 else if (cmd
->stdout_to_stderr
)
55 } else if (cmd
->out
> 1) {
60 die("chdir in start_command() not implemented");
61 if (cmd
->dir
&& chdir(cmd
->dir
))
62 die("exec %s: cd to %s failed (%s)", cmd
->argv
[0],
63 cmd
->dir
, strerror(errno
));
66 die("modifying environment for git_cmd in start_command() not implemented");
68 for (; *cmd
->env
; cmd
->env
++) {
69 if (strchr(*cmd
->env
, '='))
70 die("setting environment in start_command() not implemented");
72 env_unsetenv(env
, *cmd
->env
);
76 cmd
->pid
= spawnv_git_cmd(cmd
->argv
, fdin
, fdout
);
78 cmd
->pid
= spawnvpe_pipe(cmd
->argv
[0], cmd
->argv
, (const char**) env
, fdin
, fdout
);
86 return -ERR_RUN_COMMAND_FORK
;
92 int finish_command(struct child_process
*cmd
)
101 pid_t waiting
= waitpid(cmd
->pid
, &status
, 0);
106 error("waitpid failed (%s)", strerror(errno
));
107 return -ERR_RUN_COMMAND_WAITPID
;
109 if (waiting
!= cmd
->pid
)
110 return -ERR_RUN_COMMAND_WAITPID_WRONG_PID
;
111 if (WIFSIGNALED(status
))
112 return -ERR_RUN_COMMAND_WAITPID_SIGNAL
;
114 if (!WIFEXITED(status
))
115 return -ERR_RUN_COMMAND_WAITPID_NOEXIT
;
116 code
= WEXITSTATUS(status
);
123 int run_command(struct child_process
*cmd
)
125 int code
= start_command(cmd
);
128 return finish_command(cmd
);
131 static void prepare_run_command_v_opt(struct child_process
*cmd
,
135 memset(cmd
, 0, sizeof(*cmd
));
137 cmd
->no_stdin
= opt
& RUN_COMMAND_NO_STDIN
? 1 : 0;
138 cmd
->git_cmd
= opt
& RUN_GIT_CMD
? 1 : 0;
139 cmd
->stdout_to_stderr
= opt
& RUN_COMMAND_STDOUT_TO_STDERR
? 1 : 0;
142 int run_command_v_opt(const char **argv
, int opt
)
144 struct child_process cmd
;
145 prepare_run_command_v_opt(&cmd
, argv
, opt
);
146 return run_command(&cmd
);
149 int run_command_v_opt_cd(const char **argv
, int opt
, const char *dir
)
151 struct child_process cmd
;
152 prepare_run_command_v_opt(&cmd
, argv
, opt
);
154 return run_command(&cmd
);
157 int run_command_v_opt_cd_env(const char **argv
, int opt
, const char *dir
, const char *const *env
)
159 struct child_process cmd
;
160 prepare_run_command_v_opt(&cmd
, argv
, opt
);
163 return run_command(&cmd
);