2005-08-01 03:17:43 +08:00
|
|
|
#include "cache.h"
|
|
|
|
#include "run-command.h"
|
2006-01-11 10:12:17 +08:00
|
|
|
#include "exec_cmd.h"
|
2005-08-01 03:17:43 +08:00
|
|
|
|
2007-03-10 16:28:05 +08:00
|
|
|
int start_command(struct child_process *cmd)
|
2005-08-01 03:17:43 +08:00
|
|
|
{
|
2007-03-10 16:28:05 +08:00
|
|
|
cmd->pid = fork();
|
|
|
|
if (cmd->pid < 0)
|
2005-08-01 03:17:43 +08:00
|
|
|
return -ERR_RUN_COMMAND_FORK;
|
2007-03-10 16:28:05 +08:00
|
|
|
if (!cmd->pid) {
|
2007-03-10 16:28:00 +08:00
|
|
|
if (cmd->no_stdin) {
|
2005-12-08 10:04:38 +08:00
|
|
|
int fd = open("/dev/null", O_RDWR);
|
|
|
|
dup2(fd, 0);
|
2006-01-11 10:12:17 +08:00
|
|
|
close(fd);
|
2006-12-31 10:55:22 +08:00
|
|
|
}
|
2007-03-10 16:28:00 +08:00
|
|
|
if (cmd->stdout_to_stderr)
|
2006-12-31 10:55:19 +08:00
|
|
|
dup2(2, 1);
|
2007-03-10 16:28:00 +08:00
|
|
|
if (cmd->git_cmd) {
|
|
|
|
execv_git_cmd(cmd->argv);
|
2006-01-11 10:12:17 +08:00
|
|
|
} else {
|
2007-03-10 16:28:00 +08:00
|
|
|
execvp(cmd->argv[0], (char *const*) cmd->argv);
|
2005-12-08 10:04:38 +08:00
|
|
|
}
|
2007-03-10 16:28:00 +08:00
|
|
|
die("exec %s failed.", cmd->argv[0]);
|
2005-08-01 03:17:43 +08:00
|
|
|
}
|
2007-03-10 16:28:05 +08:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
int finish_command(struct child_process *cmd)
|
|
|
|
{
|
2005-08-01 03:17:43 +08:00
|
|
|
for (;;) {
|
|
|
|
int status, code;
|
2007-03-10 16:28:05 +08:00
|
|
|
pid_t waiting = waitpid(cmd->pid, &status, 0);
|
2005-08-01 03:17:43 +08:00
|
|
|
|
2006-08-16 01:40:06 +08:00
|
|
|
if (waiting < 0) {
|
2005-08-01 03:17:43 +08:00
|
|
|
if (errno == EINTR)
|
|
|
|
continue;
|
2006-08-16 01:40:06 +08:00
|
|
|
error("waitpid failed (%s)", strerror(errno));
|
2005-08-01 03:17:43 +08:00
|
|
|
return -ERR_RUN_COMMAND_WAITPID;
|
|
|
|
}
|
2007-03-10 16:28:05 +08:00
|
|
|
if (waiting != cmd->pid)
|
2005-08-01 03:17:43 +08:00
|
|
|
return -ERR_RUN_COMMAND_WAITPID_WRONG_PID;
|
|
|
|
if (WIFSIGNALED(status))
|
|
|
|
return -ERR_RUN_COMMAND_WAITPID_SIGNAL;
|
|
|
|
|
|
|
|
if (!WIFEXITED(status))
|
|
|
|
return -ERR_RUN_COMMAND_WAITPID_NOEXIT;
|
|
|
|
code = WEXITSTATUS(status);
|
|
|
|
if (code)
|
|
|
|
return -code;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
2007-03-10 16:28:00 +08:00
|
|
|
|
2007-03-10 16:28:05 +08:00
|
|
|
int run_command(struct child_process *cmd)
|
|
|
|
{
|
|
|
|
int code = start_command(cmd);
|
|
|
|
if (code)
|
|
|
|
return code;
|
|
|
|
return finish_command(cmd);
|
|
|
|
}
|
|
|
|
|
2007-03-10 16:28:00 +08:00
|
|
|
int run_command_v_opt(const char **argv, int opt)
|
|
|
|
{
|
|
|
|
struct child_process cmd;
|
|
|
|
memset(&cmd, 0, sizeof(cmd));
|
|
|
|
cmd.argv = argv;
|
|
|
|
cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
|
|
|
|
cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
|
|
|
|
cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
|
|
|
|
return run_command(&cmd);
|
|
|
|
}
|