2 #include "run-command.h"
4 #include "spawn-pipe.h"
7 static inline void close_pair(int fd
[2])
13 int start_command(struct child_process
*cmd
)
15 int need_in
, need_out
;
16 int fdin
[2] = { -1, -1 };
17 int fdout
[2] = { -1, -1 };
20 need_in
= !cmd
->no_stdin
&& cmd
->in
< 0;
23 return -ERR_RUN_COMMAND_PIPE
;
28 need_out
= !cmd
->no_stdout
29 && !cmd
->stdout_to_stderr
32 if (pipe(fdout
) < 0) {
35 return -ERR_RUN_COMMAND_PIPE
;
43 fdin
[0] = open("/dev/null", O_RDWR
);
51 fdout
[1] = open("/dev/null", O_RDWR
);
52 else if (cmd
->stdout_to_stderr
)
56 } else if (cmd
->out
> 1) {
61 die("chdir in start_command() not implemented");
62 if (cmd
->dir
&& chdir(cmd
->dir
))
63 die("exec %s: cd to %s failed (%s)", cmd
->argv
[0],
64 cmd
->dir
, strerror(errno
));
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
);
79 cmd
->pid
= spawnve_git_cmd(cmd
->argv
, fdin
, fdout
, env
);
81 cmd
->pid
= spawnvpe_pipe(cmd
->cmd
? cmd
->cmd
: cmd
->argv
[0], cmd
->argv
, env
, fdin
, fdout
);
89 return -ERR_RUN_COMMAND_FORK
;
95 int finish_command(struct child_process
*cmd
)
104 pid_t waiting
= waitpid(cmd
->pid
, &status
, 0);
109 error("waitpid failed (%s)", strerror(errno
));
110 return -ERR_RUN_COMMAND_WAITPID
;
112 if (waiting
!= cmd
->pid
)
113 return -ERR_RUN_COMMAND_WAITPID_WRONG_PID
;
114 if (WIFSIGNALED(status
))
115 return -ERR_RUN_COMMAND_WAITPID_SIGNAL
;
117 if (!WIFEXITED(status
))
118 return -ERR_RUN_COMMAND_WAITPID_NOEXIT
;
119 code
= WEXITSTATUS(status
);
126 int run_command(struct child_process
*cmd
)
128 int code
= start_command(cmd
);
131 return finish_command(cmd
);
134 static void prepare_run_command_v_opt(struct child_process
*cmd
,
138 memset(cmd
, 0, sizeof(*cmd
));
140 cmd
->no_stdin
= opt
& RUN_COMMAND_NO_STDIN
? 1 : 0;
141 cmd
->git_cmd
= opt
& RUN_GIT_CMD
? 1 : 0;
142 cmd
->stdout_to_stderr
= opt
& RUN_COMMAND_STDOUT_TO_STDERR
? 1 : 0;
143 cmd
->merge_env
= opt
& RUN_COMMAND_NO_MERGE_ENV
? 0 : 1;
146 int run_command_v_opt(const char **argv
, int opt
)
148 struct child_process cmd
;
149 prepare_run_command_v_opt(&cmd
, argv
, opt
);
150 return run_command(&cmd
);
153 int run_command_v_opt_cd(const char **argv
, int opt
, const char *dir
)
155 struct child_process cmd
;
156 prepare_run_command_v_opt(&cmd
, argv
, opt
);
158 return run_command(&cmd
);
161 int run_command_v_opt_cd_env(const char **argv
, int opt
, const char *dir
, const char *const *env
)
163 struct child_process cmd
;
164 prepare_run_command_v_opt(&cmd
, argv
, opt
);
167 return run_command(&cmd
);