GIT 0.99.3
[git/gitweb.git] / run-command.c
blob5117f627c86de68ed9f3da36e9e0c7b41a6e4691
1 #include "cache.h"
2 #include "run-command.h"
3 #include <sys/wait.h>
5 static int run_external_command(int argc, const char **argv)
7 pid_t pid = fork();
9 if (pid < 0)
10 return -ERR_RUN_COMMAND_FORK;
11 if (!pid) {
12 execvp(argv[0], (char *const*) argv);
13 return -ERR_RUN_COMMAND_EXEC;
15 for (;;) {
16 int status, code;
17 int retval = waitpid(pid, &status, 0);
19 if (retval < 0) {
20 if (errno == EINTR)
21 continue;
22 error("waitpid failed (%s)", strerror(retval));
23 return -ERR_RUN_COMMAND_WAITPID;
25 if (retval != pid)
26 return -ERR_RUN_COMMAND_WAITPID_WRONG_PID;
27 if (WIFSIGNALED(status))
28 return -ERR_RUN_COMMAND_WAITPID_SIGNAL;
30 if (!WIFEXITED(status))
31 return -ERR_RUN_COMMAND_WAITPID_NOEXIT;
32 code = WEXITSTATUS(status);
33 if (code)
34 return -code;
35 return 0;
39 int run_command(const char *cmd, ...)
41 int argc;
42 const char *argv[MAX_RUN_COMMAND_ARGS];
43 const char *arg;
44 va_list param;
46 fprintf(stderr, "run-command %s (%d)\n", cmd, ERR_RUN_COMMAND_EXEC);
48 va_start(param, cmd);
49 argv[0] = cmd;
50 argc = 1;
51 while (argc < MAX_RUN_COMMAND_ARGS) {
52 arg = argv[argc++] = va_arg(param, char *);
53 if (!arg)
54 break;
56 va_end(param);
57 if (MAX_RUN_COMMAND_ARGS <= argc)
58 return error("too many args to run %s", cmd);
59 return run_external_command(argc, argv);