2 #include "run-command.h"
5 #include "argv-array.h"
6 #include "thread-utils.h"
9 void child_process_init(struct child_process *child)
11 memset(child, 0, sizeof(*child));
12 argv_array_init(&child->args);
13 argv_array_init(&child->env_array);
16 void child_process_clear(struct child_process *child)
18 argv_array_clear(&child->args);
19 argv_array_clear(&child->env_array);
22 struct child_to_clean {
24 struct child_process *process;
25 struct child_to_clean *next;
27 static struct child_to_clean *children_to_clean;
28 static int installed_child_cleanup_handler;
30 static void cleanup_children(int sig, int in_signal)
32 struct child_to_clean *children_to_wait_for = NULL;
34 while (children_to_clean) {
35 struct child_to_clean *p = children_to_clean;
36 children_to_clean = p->next;
38 if (p->process && !in_signal) {
39 struct child_process *process = p->process;
40 if (process->clean_on_exit_handler) {
42 "trace: run_command: running exit handler for pid %"
43 PRIuMAX, (uintmax_t)p->pid
45 process->clean_on_exit_handler(process);
51 if (p->process && p->process->wait_after_clean) {
52 p->next = children_to_wait_for;
53 children_to_wait_for = p;
60 while (children_to_wait_for) {
61 struct child_to_clean *p = children_to_wait_for;
62 children_to_wait_for = p->next;
64 while (waitpid(p->pid, NULL, 0) < 0 && errno == EINTR)
65 ; /* spin waiting for process exit or error */
72 static void cleanup_children_on_signal(int sig)
74 cleanup_children(sig, 1);
79 static void cleanup_children_on_exit(void)
81 cleanup_children(SIGTERM, 0);
84 static void mark_child_for_cleanup(pid_t pid, struct child_process *process)
86 struct child_to_clean *p = xmalloc(sizeof(*p));
89 p->next = children_to_clean;
90 children_to_clean = p;
92 if (!installed_child_cleanup_handler) {
93 atexit(cleanup_children_on_exit);
94 sigchain_push_common(cleanup_children_on_signal);
95 installed_child_cleanup_handler = 1;
99 static void clear_child_for_cleanup(pid_t pid)
101 struct child_to_clean **pp;
103 for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
104 struct child_to_clean *clean_me = *pp;
106 if (clean_me->pid == pid) {
107 *pp = clean_me->next;
114 static inline void close_pair(int fd[2])
120 static char *locate_in_PATH(const char *file)
122 const char *p = getenv("PATH");
123 struct strbuf buf = STRBUF_INIT;
129 const char *end = strchrnul(p, ':');
133 /* POSIX specifies an empty entry as the current directory. */
135 strbuf_add(&buf, p, end - p);
136 strbuf_addch(&buf, '/');
138 strbuf_addstr(&buf, file);
140 if (!access(buf.buf, F_OK))
141 return strbuf_detach(&buf, NULL);
148 strbuf_release(&buf);
152 static int exists_in_PATH(const char *file)
154 char *r = locate_in_PATH(file);
159 int sane_execvp(const char *file, char * const argv[])
161 if (!execvp(file, argv))
162 return 0; /* cannot happen ;-) */
165 * When a command can't be found because one of the directories
166 * listed in $PATH is unsearchable, execvp reports EACCES, but
167 * careful usability testing (read: analysis of occasional bug
168 * reports) reveals that "No such file or directory" is more
171 * We avoid commands with "/", because execvp will not do $PATH
172 * lookups in that case.
174 * The reassignment of EACCES to errno looks like a no-op below,
175 * but we need to protect against exists_in_PATH overwriting errno.
177 if (errno == EACCES && !strchr(file, '/'))
178 errno = exists_in_PATH(file) ? EACCES : ENOENT;
179 else if (errno == ENOTDIR && !strchr(file, '/'))
184 static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
187 die("BUG: shell command is empty");
189 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
190 #ifndef GIT_WINDOWS_NATIVE
191 argv_array_push(out, SHELL_PATH);
193 argv_array_push(out, "sh");
195 argv_array_push(out, "-c");
198 * If we have no extra arguments, we do not even need to
199 * bother with the "$@" magic.
202 argv_array_push(out, argv[0]);
204 argv_array_pushf(out, "%s \"$@\"", argv[0]);
207 argv_array_pushv(out, argv);
211 #ifndef GIT_WINDOWS_NATIVE
212 static int child_notifier = -1;
222 enum child_errcode err;
223 int syserr; /* errno */
226 static void child_die(enum child_errcode err)
228 struct child_err buf;
233 /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
234 xwrite(child_notifier, &buf, sizeof(buf));
239 * parent will make it look like the child spewed a fatal error and died
240 * this is needed to prevent changes to t0061.
242 static void fake_fatal(const char *err, va_list params)
244 vreportf("fatal: ", err, params);
247 static void child_error_fn(const char *err, va_list params)
249 const char msg[] = "error() should not be called in child\n";
250 xwrite(2, msg, sizeof(msg) - 1);
253 static void child_warn_fn(const char *err, va_list params)
255 const char msg[] = "warn() should not be called in child\n";
256 xwrite(2, msg, sizeof(msg) - 1);
259 static void NORETURN child_die_fn(const char *err, va_list params)
261 const char msg[] = "die() should not be called in child\n";
262 xwrite(2, msg, sizeof(msg) - 1);
266 /* this runs in the parent process */
267 static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
269 static void (*old_errfn)(const char *err, va_list params);
271 old_errfn = get_error_routine();
272 set_error_routine(fake_fatal);
273 errno = cerr->syserr;
276 case CHILD_ERR_CHDIR:
277 error_errno("exec '%s': cd to '%s' failed",
278 cmd->argv[0], cmd->dir);
280 case CHILD_ERR_ENOENT:
281 error_errno("cannot run %s", cmd->argv[0]);
283 case CHILD_ERR_SILENT:
285 case CHILD_ERR_ERRNO:
286 error_errno("cannot exec '%s'", cmd->argv[0]);
289 set_error_routine(old_errfn);
292 static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
295 die("BUG: command is empty");
298 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
299 * attempt to interpret the command with 'sh'.
301 argv_array_push(out, SHELL_PATH);
304 argv_array_push(out, "git");
305 argv_array_pushv(out, cmd->argv);
306 } else if (cmd->use_shell) {
307 prepare_shell_cmd(out, cmd->argv);
309 argv_array_pushv(out, cmd->argv);
313 * If there are no '/' characters in the command then perform a path
314 * lookup and use the resolved path as the command to exec. If there
315 * are no '/' characters or if the command wasn't found in the path,
316 * have exec attempt to invoke the command directly.
318 if (!strchr(out->argv[1], '/')) {
319 char *program = locate_in_PATH(out->argv[1]);
321 free((char *)out->argv[1]);
322 out->argv[1] = program;
327 static char **prep_childenv(const char *const *deltaenv)
329 extern char **environ;
331 struct string_list env = STRING_LIST_INIT_DUP;
332 struct strbuf key = STRBUF_INIT;
333 const char *const *p;
336 /* Construct a sorted string list consisting of the current environ */
337 for (p = (const char *const *) environ; p && *p; p++) {
338 const char *equals = strchr(*p, '=');
342 strbuf_add(&key, *p, equals - *p);
343 string_list_append(&env, key.buf)->util = (void *) *p;
345 string_list_append(&env, *p)->util = (void *) *p;
348 string_list_sort(&env);
350 /* Merge in 'deltaenv' with the current environ */
351 for (p = deltaenv; p && *p; p++) {
352 const char *equals = strchr(*p, '=');
355 /* ('key=value'), insert or replace entry */
357 strbuf_add(&key, *p, equals - *p);
358 string_list_insert(&env, key.buf)->util = (void *) *p;
360 /* otherwise ('key') remove existing entry */
361 string_list_remove(&env, *p, 0);
365 /* Create an array of 'char *' to be used as the childenv */
366 childenv = xmalloc((env.nr + 1) * sizeof(char *));
367 for (i = 0; i < env.nr; i++)
368 childenv[i] = env.items[i].util;
369 childenv[env.nr] = NULL;
371 string_list_clear(&env, 0);
372 strbuf_release(&key);
377 static inline void set_cloexec(int fd)
379 int flags = fcntl(fd, F_GETFD);
381 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
384 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
386 int status, code = -1;
388 int failed_errno = 0;
390 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
396 failed_errno = errno;
397 error_errno("waitpid for %s failed", argv0);
398 } else if (waiting != pid) {
399 error("waitpid is confused (%s)", argv0);
400 } else if (WIFSIGNALED(status)) {
401 code = WTERMSIG(status);
402 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
403 error("%s died of signal %d", argv0, code);
405 * This return value is chosen so that code & 0xff
406 * mimics the exit code that a POSIX shell would report for
407 * a program that died from this signal.
410 } else if (WIFEXITED(status)) {
411 code = WEXITSTATUS(status);
413 error("waitpid is confused (%s)", argv0);
416 clear_child_for_cleanup(pid);
418 errno = failed_errno;
422 int start_command(struct child_process *cmd)
424 int need_in, need_out, need_err;
425 int fdin[2], fdout[2], fderr[2];
430 cmd->argv = cmd->args.argv;
432 cmd->env = cmd->env_array.argv;
435 * In case of errors we must keep the promise to close FDs
436 * that have been passed in via ->in and ->out.
439 need_in = !cmd->no_stdin && cmd->in < 0;
441 if (pipe(fdin) < 0) {
442 failed_errno = errno;
445 str = "standard input";
451 need_out = !cmd->no_stdout
452 && !cmd->stdout_to_stderr
455 if (pipe(fdout) < 0) {
456 failed_errno = errno;
461 str = "standard output";
467 need_err = !cmd->no_stderr && cmd->err < 0;
469 if (pipe(fderr) < 0) {
470 failed_errno = errno;
479 str = "standard error";
481 error("cannot create %s pipe for %s: %s",
482 str, cmd->argv[0], strerror(failed_errno));
483 child_process_clear(cmd);
484 errno = failed_errno;
490 trace_argv_printf(cmd->argv, "trace: run_command:");
493 #ifndef GIT_WINDOWS_NATIVE
498 struct argv_array argv = ARGV_ARRAY_INIT;
499 struct child_err cerr;
501 if (pipe(notify_pipe))
502 notify_pipe[0] = notify_pipe[1] = -1;
504 if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
505 null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);
507 die_errno(_("open /dev/null failed"));
508 set_cloexec(null_fd);
511 prepare_cmd(&argv, cmd);
512 childenv = prep_childenv(cmd->env);
515 failed_errno = errno;
518 * Ensure the default die/error/warn routines do not get
519 * called, they can take stdio locks and malloc.
521 set_die_routine(child_die_fn);
522 set_error_routine(child_error_fn);
523 set_warn_routine(child_warn_fn);
525 close(notify_pipe[0]);
526 set_cloexec(notify_pipe[1]);
527 child_notifier = notify_pipe[1];
534 } else if (cmd->in) {
544 } else if (cmd->err > 1) {
551 else if (cmd->stdout_to_stderr)
556 } else if (cmd->out > 1) {
561 if (cmd->dir && chdir(cmd->dir))
562 child_die(CHILD_ERR_CHDIR);
565 * Attempt to exec using the command and arguments starting at
566 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
567 * be used in the event exec failed with ENOEXEC at which point
568 * we will try to interpret the command using 'sh'.
570 execve(argv.argv[1], (char *const *) argv.argv + 1,
571 (char *const *) childenv);
572 if (errno == ENOEXEC)
573 execve(argv.argv[0], (char *const *) argv.argv,
574 (char *const *) childenv);
576 if (errno == ENOENT) {
577 if (cmd->silent_exec_failure)
578 child_die(CHILD_ERR_SILENT);
579 child_die(CHILD_ERR_ENOENT);
581 child_die(CHILD_ERR_ERRNO);
585 error_errno("cannot fork() for %s", cmd->argv[0]);
586 else if (cmd->clean_on_exit)
587 mark_child_for_cleanup(cmd->pid, cmd);
590 * Wait for child's exec. If the exec succeeds (or if fork()
591 * failed), EOF is seen immediately by the parent. Otherwise, the
592 * child process sends a child_err struct.
593 * Note that use of this infrastructure is completely advisory,
594 * therefore, we keep error checks minimal.
596 close(notify_pipe[1]);
597 if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
599 * At this point we know that fork() succeeded, but exec()
600 * failed. Errors have been reported to our stderr.
602 wait_or_whine(cmd->pid, cmd->argv[0], 0);
603 child_err_spew(cmd, &cerr);
604 failed_errno = errno;
607 close(notify_pipe[0]);
611 argv_array_clear(&argv);
616 int fhin = 0, fhout = 1, fherr = 2;
617 const char **sargv = cmd->argv;
618 struct argv_array nargv = ARGV_ARRAY_INIT;
621 fhin = open("/dev/null", O_RDWR);
628 fherr = open("/dev/null", O_RDWR);
630 fherr = dup(fderr[1]);
631 else if (cmd->err > 2)
632 fherr = dup(cmd->err);
635 fhout = open("/dev/null", O_RDWR);
636 else if (cmd->stdout_to_stderr)
639 fhout = dup(fdout[1]);
640 else if (cmd->out > 1)
641 fhout = dup(cmd->out);
644 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
645 else if (cmd->use_shell)
646 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
648 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
649 cmd->dir, fhin, fhout, fherr);
650 failed_errno = errno;
651 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
652 error_errno("cannot spawn %s", cmd->argv[0]);
653 if (cmd->clean_on_exit && cmd->pid >= 0)
654 mark_child_for_cleanup(cmd->pid, cmd);
656 argv_array_clear(&nargv);
680 child_process_clear(cmd);
681 errno = failed_errno;
703 int finish_command(struct child_process *cmd)
705 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
706 child_process_clear(cmd);
710 int finish_command_in_signal(struct child_process *cmd)
712 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
716 int run_command(struct child_process *cmd)
720 if (cmd->out < 0 || cmd->err < 0)
721 die("BUG: run_command with a pipe can cause deadlock");
723 code = start_command(cmd);
726 return finish_command(cmd);
729 int run_command_v_opt(const char **argv, int opt)
731 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
734 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
736 struct child_process cmd = CHILD_PROCESS_INIT;
738 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
739 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
740 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
741 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
742 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
743 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
746 return run_command(&cmd);
750 static pthread_t main_thread;
751 static int main_thread_set;
752 static pthread_key_t async_key;
753 static pthread_key_t async_die_counter;
755 static void *run_thread(void *data)
757 struct async *async = data;
760 if (async->isolate_sigpipe) {
763 sigaddset(&mask, SIGPIPE);
764 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
765 ret = error("unable to block SIGPIPE in async thread");
770 pthread_setspecific(async_key, async);
771 ret = async->proc(async->proc_in, async->proc_out, async->data);
775 static NORETURN void die_async(const char *err, va_list params)
777 vreportf("fatal: ", err, params);
780 struct async *async = pthread_getspecific(async_key);
781 if (async->proc_in >= 0)
782 close(async->proc_in);
783 if (async->proc_out >= 0)
784 close(async->proc_out);
785 pthread_exit((void *)128);
791 static int async_die_is_recursing(void)
793 void *ret = pthread_getspecific(async_die_counter);
794 pthread_setspecific(async_die_counter, (void *)1);
800 if (!main_thread_set)
801 return 0; /* no asyncs started yet */
802 return !pthread_equal(main_thread, pthread_self());
805 static void NORETURN async_exit(int code)
807 pthread_exit((void *)(intptr_t)code);
813 void (**handlers)(void);
818 static int git_atexit_installed;
820 static void git_atexit_dispatch(void)
824 for (i=git_atexit_hdlrs.nr ; i ; i--)
825 git_atexit_hdlrs.handlers[i-1]();
828 static void git_atexit_clear(void)
830 free(git_atexit_hdlrs.handlers);
831 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
832 git_atexit_installed = 0;
836 int git_atexit(void (*handler)(void))
838 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
839 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
840 if (!git_atexit_installed) {
841 if (atexit(&git_atexit_dispatch))
843 git_atexit_installed = 1;
847 #define atexit git_atexit
849 static int process_is_async;
852 return process_is_async;
855 static void NORETURN async_exit(int code)
862 void check_pipe(int err)
868 signal(SIGPIPE, SIG_DFL);
870 /* Should never happen, but just in case... */
875 int start_async(struct async *async)
877 int need_in, need_out;
878 int fdin[2], fdout[2];
879 int proc_in, proc_out;
881 need_in = async->in < 0;
883 if (pipe(fdin) < 0) {
886 return error_errno("cannot create pipe");
891 need_out = async->out < 0;
893 if (pipe(fdout) < 0) {
898 return error_errno("cannot create pipe");
900 async->out = fdout[0];
913 proc_out = async->out;
918 /* Flush stdio before fork() to avoid cloning buffers */
922 if (async->pid < 0) {
923 error_errno("fork (async) failed");
932 process_is_async = 1;
933 exit(!!async->proc(proc_in, proc_out, async->data));
936 mark_child_for_cleanup(async->pid, NULL);
948 if (!main_thread_set) {
950 * We assume that the first time that start_async is called
951 * it is from the main thread.
954 main_thread = pthread_self();
955 pthread_key_create(&async_key, NULL);
956 pthread_key_create(&async_die_counter, NULL);
957 set_die_routine(die_async);
958 set_die_is_recursing_routine(async_die_is_recursing);
962 set_cloexec(proc_in);
964 set_cloexec(proc_out);
965 async->proc_in = proc_in;
966 async->proc_out = proc_out;
968 int err = pthread_create(&async->tid, NULL, run_thread, async);
970 error_errno("cannot create thread");
990 int finish_async(struct async *async)
993 return wait_or_whine(async->pid, "child process", 0);
995 void *ret = (void *)(intptr_t)(-1);
997 if (pthread_join(async->tid, &ret))
998 error("pthread_join failed");
999 return (int)(intptr_t)ret;
1003 const char *find_hook(const char *name)
1005 static struct strbuf path = STRBUF_INIT;
1007 strbuf_reset(&path);
1008 strbuf_git_path(&path, "hooks/%s", name);
1009 if (access(path.buf, X_OK) < 0) {
1010 #ifdef STRIP_EXTENSION
1011 strbuf_addstr(&path, STRIP_EXTENSION);
1012 if (access(path.buf, X_OK) >= 0)
1020 int run_hook_ve(const char *const *env, const char *name, va_list args)
1022 struct child_process hook = CHILD_PROCESS_INIT;
1025 p = find_hook(name);
1029 argv_array_push(&hook.args, p);
1030 while ((p = va_arg(args, const char *)))
1031 argv_array_push(&hook.args, p);
1034 hook.stdout_to_stderr = 1;
1036 return run_command(&hook);
1039 int run_hook_le(const char *const *env, const char *name, ...)
1044 va_start(args, name);
1045 ret = run_hook_ve(env, name, args);
1052 /* initialized by caller */
1054 int type; /* POLLOUT or POLLIN */
1066 /* returned by pump_io */
1067 int error; /* 0 for success, otherwise errno */
1073 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1078 for (i = 0; i < nr; i++) {
1079 struct io_pump *io = &slots[i];
1082 pfd[pollsize].fd = io->fd;
1083 pfd[pollsize].events = io->type;
1084 io->pfd = &pfd[pollsize++];
1090 if (poll(pfd, pollsize, -1) < 0) {
1093 die_errno("poll failed");
1096 for (i = 0; i < nr; i++) {
1097 struct io_pump *io = &slots[i];
1102 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1105 if (io->type == POLLOUT) {
1106 ssize_t len = xwrite(io->fd,
1107 io->u.out.buf, io->u.out.len);
1113 io->u.out.buf += len;
1114 io->u.out.len -= len;
1115 if (!io->u.out.len) {
1122 if (io->type == POLLIN) {
1123 ssize_t len = strbuf_read_once(io->u.in.buf,
1124 io->fd, io->u.in.hint);
1137 static int pump_io(struct io_pump *slots, int nr)
1142 for (i = 0; i < nr; i++)
1145 ALLOC_ARRAY(pfd, nr);
1146 while (pump_io_round(slots, nr, pfd))
1150 /* There may be multiple errno values, so just pick the first. */
1151 for (i = 0; i < nr; i++) {
1152 if (slots[i].error) {
1153 errno = slots[i].error;
1161 int pipe_command(struct child_process *cmd,
1162 const char *in, size_t in_len,
1163 struct strbuf *out, size_t out_hint,
1164 struct strbuf *err, size_t err_hint)
1166 struct io_pump io[3];
1176 if (start_command(cmd) < 0)
1180 io[nr].fd = cmd->in;
1181 io[nr].type = POLLOUT;
1182 io[nr].u.out.buf = in;
1183 io[nr].u.out.len = in_len;
1187 io[nr].fd = cmd->out;
1188 io[nr].type = POLLIN;
1189 io[nr].u.in.buf = out;
1190 io[nr].u.in.hint = out_hint;
1194 io[nr].fd = cmd->err;
1195 io[nr].type = POLLIN;
1196 io[nr].u.in.buf = err;
1197 io[nr].u.in.hint = err_hint;
1201 if (pump_io(io, nr) < 0) {
1202 finish_command(cmd); /* throw away exit code */
1206 return finish_command(cmd);
1212 GIT_CP_WAIT_CLEANUP,
1215 struct parallel_processes {
1221 get_next_task_fn get_next_task;
1222 start_failure_fn start_failure;
1223 task_finished_fn task_finished;
1226 enum child_state state;
1227 struct child_process process;
1232 * The struct pollfd is logically part of *children,
1233 * but the system call expects it as its own array.
1237 unsigned shutdown : 1;
1240 struct strbuf buffered_output; /* of finished children */
1243 static int default_start_failure(struct strbuf *out,
1250 static int default_task_finished(int result,
1258 static void kill_children(struct parallel_processes *pp, int signo)
1260 int i, n = pp->max_processes;
1262 for (i = 0; i < n; i++)
1263 if (pp->children[i].state == GIT_CP_WORKING)
1264 kill(pp->children[i].process.pid, signo);
1267 static struct parallel_processes *pp_for_signal;
1269 static void handle_children_on_signal(int signo)
1271 kill_children(pp_for_signal, signo);
1272 sigchain_pop(signo);
1276 static void pp_init(struct parallel_processes *pp,
1278 get_next_task_fn get_next_task,
1279 start_failure_fn start_failure,
1280 task_finished_fn task_finished,
1288 pp->max_processes = n;
1290 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1294 die("BUG: you need to specify a get_next_task function");
1295 pp->get_next_task = get_next_task;
1297 pp->start_failure = start_failure ? start_failure : default_start_failure;
1298 pp->task_finished = task_finished ? task_finished : default_task_finished;
1300 pp->nr_processes = 0;
1301 pp->output_owner = 0;
1303 pp->children = xcalloc(n, sizeof(*pp->children));
1304 pp->pfd = xcalloc(n, sizeof(*pp->pfd));
1305 strbuf_init(&pp->buffered_output, 0);
1307 for (i = 0; i < n; i++) {
1308 strbuf_init(&pp->children[i].err, 0);
1309 child_process_init(&pp->children[i].process);
1310 pp->pfd[i].events = POLLIN | POLLHUP;
1315 sigchain_push_common(handle_children_on_signal);
1318 static void pp_cleanup(struct parallel_processes *pp)
1322 trace_printf("run_processes_parallel: done");
1323 for (i = 0; i < pp->max_processes; i++) {
1324 strbuf_release(&pp->children[i].err);
1325 child_process_clear(&pp->children[i].process);
1332 * When get_next_task added messages to the buffer in its last
1333 * iteration, the buffered output is non empty.
1335 strbuf_write(&pp->buffered_output, stderr);
1336 strbuf_release(&pp->buffered_output);
1338 sigchain_pop_common();
1342 * 0 if a new task was started.
1343 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1344 * problem with starting a new command)
1345 * <0 no new job was started, user wishes to shutdown early. Use negative code
1346 * to signal the children.
1348 static int pp_start_one(struct parallel_processes *pp)
1352 for (i = 0; i < pp->max_processes; i++)
1353 if (pp->children[i].state == GIT_CP_FREE)
1355 if (i == pp->max_processes)
1356 die("BUG: bookkeeping is hard");
1358 code = pp->get_next_task(&pp->children[i].process,
1359 &pp->children[i].err,
1361 &pp->children[i].data);
1363 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1364 strbuf_reset(&pp->children[i].err);
1367 pp->children[i].process.err = -1;
1368 pp->children[i].process.stdout_to_stderr = 1;
1369 pp->children[i].process.no_stdin = 1;
1371 if (start_command(&pp->children[i].process)) {
1372 code = pp->start_failure(&pp->children[i].err,
1374 &pp->children[i].data);
1375 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1376 strbuf_reset(&pp->children[i].err);
1383 pp->children[i].state = GIT_CP_WORKING;
1384 pp->pfd[i].fd = pp->children[i].process.err;
1388 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1392 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1399 /* Buffer output from all pipes. */
1400 for (i = 0; i < pp->max_processes; i++) {
1401 if (pp->children[i].state == GIT_CP_WORKING &&
1402 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1403 int n = strbuf_read_once(&pp->children[i].err,
1404 pp->children[i].process.err, 0);
1406 close(pp->children[i].process.err);
1407 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1409 if (errno != EAGAIN)
1415 static void pp_output(struct parallel_processes *pp)
1417 int i = pp->output_owner;
1418 if (pp->children[i].state == GIT_CP_WORKING &&
1419 pp->children[i].err.len) {
1420 strbuf_write(&pp->children[i].err, stderr);
1421 strbuf_reset(&pp->children[i].err);
1425 static int pp_collect_finished(struct parallel_processes *pp)
1428 int n = pp->max_processes;
1431 while (pp->nr_processes > 0) {
1432 for (i = 0; i < pp->max_processes; i++)
1433 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1435 if (i == pp->max_processes)
1438 code = finish_command(&pp->children[i].process);
1440 code = pp->task_finished(code,
1441 &pp->children[i].err, pp->data,
1442 &pp->children[i].data);
1450 pp->children[i].state = GIT_CP_FREE;
1452 child_process_init(&pp->children[i].process);
1454 if (i != pp->output_owner) {
1455 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1456 strbuf_reset(&pp->children[i].err);
1458 strbuf_write(&pp->children[i].err, stderr);
1459 strbuf_reset(&pp->children[i].err);
1461 /* Output all other finished child processes */
1462 strbuf_write(&pp->buffered_output, stderr);
1463 strbuf_reset(&pp->buffered_output);
1466 * Pick next process to output live.
1468 * For now we pick it randomly by doing a round
1469 * robin. Later we may want to pick the one with
1470 * the most output or the longest or shortest
1471 * running process time.
1473 for (i = 0; i < n; i++)
1474 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1476 pp->output_owner = (pp->output_owner + i) % n;
1482 int run_processes_parallel(int n,
1483 get_next_task_fn get_next_task,
1484 start_failure_fn start_failure,
1485 task_finished_fn task_finished,
1489 int output_timeout = 100;
1491 struct parallel_processes pp;
1493 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1496 i < spawn_cap && !pp.shutdown &&
1497 pp.nr_processes < pp.max_processes;
1499 code = pp_start_one(&pp);
1504 kill_children(&pp, -code);
1508 if (!pp.nr_processes)
1510 pp_buffer_stderr(&pp, output_timeout);
1512 code = pp_collect_finished(&pp);
1516 kill_children(&pp, -code);