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 #ifndef GIT_WINDOWS_NATIVE
121 static inline void dup_devnull(int to)
123 int fd = open("/dev/null", O_RDWR);
125 die_errno(_("open /dev/null failed"));
126 if (dup2(fd, to) < 0)
127 die_errno(_("dup2(%d,%d) failed"), fd, to);
132 static char *locate_in_PATH(const char *file)
134 const char *p = getenv("PATH");
135 struct strbuf buf = STRBUF_INIT;
141 const char *end = strchrnul(p, ':');
145 /* POSIX specifies an empty entry as the current directory. */
147 strbuf_add(&buf, p, end - p);
148 strbuf_addch(&buf, '/');
150 strbuf_addstr(&buf, file);
152 if (!access(buf.buf, F_OK))
153 return strbuf_detach(&buf, NULL);
160 strbuf_release(&buf);
164 static int exists_in_PATH(const char *file)
166 char *r = locate_in_PATH(file);
171 int sane_execvp(const char *file, char * const argv[])
173 if (!execvp(file, argv))
174 return 0; /* cannot happen ;-) */
177 * When a command can't be found because one of the directories
178 * listed in $PATH is unsearchable, execvp reports EACCES, but
179 * careful usability testing (read: analysis of occasional bug
180 * reports) reveals that "No such file or directory" is more
183 * We avoid commands with "/", because execvp will not do $PATH
184 * lookups in that case.
186 * The reassignment of EACCES to errno looks like a no-op below,
187 * but we need to protect against exists_in_PATH overwriting errno.
189 if (errno == EACCES && !strchr(file, '/'))
190 errno = exists_in_PATH(file) ? EACCES : ENOENT;
191 else if (errno == ENOTDIR && !strchr(file, '/'))
196 static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
199 die("BUG: shell command is empty");
201 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
202 #ifndef GIT_WINDOWS_NATIVE
203 argv_array_push(out, SHELL_PATH);
205 argv_array_push(out, "sh");
207 argv_array_push(out, "-c");
210 * If we have no extra arguments, we do not even need to
211 * bother with the "$@" magic.
214 argv_array_push(out, argv[0]);
216 argv_array_pushf(out, "%s \"$@\"", argv[0]);
219 argv_array_pushv(out, argv);
223 #ifndef GIT_WINDOWS_NATIVE
224 static int child_notifier = -1;
226 static void notify_parent(void)
229 * execvp failed. If possible, we'd like to let start_command
230 * know, so failures like ENOENT can be handled right away; but
231 * otherwise, finish_command will still report the error.
233 xwrite(child_notifier, "", 1);
236 static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
239 die("BUG: command is empty");
242 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
243 * attempt to interpret the command with 'sh'.
245 argv_array_push(out, SHELL_PATH);
248 argv_array_push(out, "git");
249 argv_array_pushv(out, cmd->argv);
250 } else if (cmd->use_shell) {
251 prepare_shell_cmd(out, cmd->argv);
253 argv_array_pushv(out, cmd->argv);
257 * If there are no '/' characters in the command then perform a path
258 * lookup and use the resolved path as the command to exec. If there
259 * are no '/' characters or if the command wasn't found in the path,
260 * have exec attempt to invoke the command directly.
262 if (!strchr(out->argv[1], '/')) {
263 char *program = locate_in_PATH(out->argv[1]);
265 free((char *)out->argv[1]);
266 out->argv[1] = program;
272 static inline void set_cloexec(int fd)
274 int flags = fcntl(fd, F_GETFD);
276 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
279 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
281 int status, code = -1;
283 int failed_errno = 0;
285 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
291 failed_errno = errno;
292 error_errno("waitpid for %s failed", argv0);
293 } else if (waiting != pid) {
294 error("waitpid is confused (%s)", argv0);
295 } else if (WIFSIGNALED(status)) {
296 code = WTERMSIG(status);
297 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
298 error("%s died of signal %d", argv0, code);
300 * This return value is chosen so that code & 0xff
301 * mimics the exit code that a POSIX shell would report for
302 * a program that died from this signal.
305 } else if (WIFEXITED(status)) {
306 code = WEXITSTATUS(status);
308 * Convert special exit code when execvp failed.
312 failed_errno = ENOENT;
315 error("waitpid is confused (%s)", argv0);
318 clear_child_for_cleanup(pid);
320 errno = failed_errno;
324 int start_command(struct child_process *cmd)
326 int need_in, need_out, need_err;
327 int fdin[2], fdout[2], fderr[2];
332 cmd->argv = cmd->args.argv;
334 cmd->env = cmd->env_array.argv;
337 * In case of errors we must keep the promise to close FDs
338 * that have been passed in via ->in and ->out.
341 need_in = !cmd->no_stdin && cmd->in < 0;
343 if (pipe(fdin) < 0) {
344 failed_errno = errno;
347 str = "standard input";
353 need_out = !cmd->no_stdout
354 && !cmd->stdout_to_stderr
357 if (pipe(fdout) < 0) {
358 failed_errno = errno;
363 str = "standard output";
369 need_err = !cmd->no_stderr && cmd->err < 0;
371 if (pipe(fderr) < 0) {
372 failed_errno = errno;
381 str = "standard error";
383 error("cannot create %s pipe for %s: %s",
384 str, cmd->argv[0], strerror(failed_errno));
385 child_process_clear(cmd);
386 errno = failed_errno;
392 trace_argv_printf(cmd->argv, "trace: run_command:");
395 #ifndef GIT_WINDOWS_NATIVE
398 struct argv_array argv = ARGV_ARRAY_INIT;
400 if (pipe(notify_pipe))
401 notify_pipe[0] = notify_pipe[1] = -1;
403 prepare_cmd(&argv, cmd);
406 failed_errno = errno;
409 * Redirect the channel to write syscall error messages to
410 * before redirecting the process's stderr so that all die()
411 * in subsequent call paths use the parent's stderr.
413 if (cmd->no_stderr || need_err) {
414 int child_err = dup(2);
415 set_cloexec(child_err);
416 set_error_handle(fdopen(child_err, "w"));
419 close(notify_pipe[0]);
420 set_cloexec(notify_pipe[1]);
421 child_notifier = notify_pipe[1];
422 atexit(notify_parent);
429 } else if (cmd->in) {
439 } else if (cmd->err > 1) {
446 else if (cmd->stdout_to_stderr)
451 } else if (cmd->out > 1) {
456 if (cmd->dir && chdir(cmd->dir))
457 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
460 for (; *cmd->env; cmd->env++) {
461 if (strchr(*cmd->env, '='))
462 putenv((char *)*cmd->env);
469 * Attempt to exec using the command and arguments starting at
470 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
471 * be used in the event exec failed with ENOEXEC at which point
472 * we will try to interpret the command using 'sh'.
474 execv(argv.argv[1], (char *const *) argv.argv + 1);
475 if (errno == ENOEXEC)
476 execv(argv.argv[0], (char *const *) argv.argv);
478 if (errno == ENOENT) {
479 if (!cmd->silent_exec_failure)
480 error("cannot run %s: %s", cmd->argv[0],
484 die_errno("cannot exec '%s'", cmd->argv[0]);
488 error_errno("cannot fork() for %s", cmd->argv[0]);
489 else if (cmd->clean_on_exit)
490 mark_child_for_cleanup(cmd->pid, cmd);
493 * Wait for child's exec. If the exec succeeds (or if fork()
494 * failed), EOF is seen immediately by the parent. Otherwise, the
495 * child process sends a single byte.
496 * Note that use of this infrastructure is completely advisory,
497 * therefore, we keep error checks minimal.
499 close(notify_pipe[1]);
500 if (read(notify_pipe[0], ¬ify_pipe[1], 1) == 1) {
502 * At this point we know that fork() succeeded, but exec()
503 * failed. Errors have been reported to our stderr.
505 wait_or_whine(cmd->pid, cmd->argv[0], 0);
506 failed_errno = errno;
509 close(notify_pipe[0]);
511 argv_array_clear(&argv);
515 int fhin = 0, fhout = 1, fherr = 2;
516 const char **sargv = cmd->argv;
517 struct argv_array nargv = ARGV_ARRAY_INIT;
520 fhin = open("/dev/null", O_RDWR);
527 fherr = open("/dev/null", O_RDWR);
529 fherr = dup(fderr[1]);
530 else if (cmd->err > 2)
531 fherr = dup(cmd->err);
534 fhout = open("/dev/null", O_RDWR);
535 else if (cmd->stdout_to_stderr)
538 fhout = dup(fdout[1]);
539 else if (cmd->out > 1)
540 fhout = dup(cmd->out);
543 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
544 else if (cmd->use_shell)
545 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
547 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
548 cmd->dir, fhin, fhout, fherr);
549 failed_errno = errno;
550 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
551 error_errno("cannot spawn %s", cmd->argv[0]);
552 if (cmd->clean_on_exit && cmd->pid >= 0)
553 mark_child_for_cleanup(cmd->pid, cmd);
555 argv_array_clear(&nargv);
579 child_process_clear(cmd);
580 errno = failed_errno;
602 int finish_command(struct child_process *cmd)
604 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
605 child_process_clear(cmd);
609 int finish_command_in_signal(struct child_process *cmd)
611 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
615 int run_command(struct child_process *cmd)
619 if (cmd->out < 0 || cmd->err < 0)
620 die("BUG: run_command with a pipe can cause deadlock");
622 code = start_command(cmd);
625 return finish_command(cmd);
628 int run_command_v_opt(const char **argv, int opt)
630 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
633 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
635 struct child_process cmd = CHILD_PROCESS_INIT;
637 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
638 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
639 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
640 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
641 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
642 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
645 return run_command(&cmd);
649 static pthread_t main_thread;
650 static int main_thread_set;
651 static pthread_key_t async_key;
652 static pthread_key_t async_die_counter;
654 static void *run_thread(void *data)
656 struct async *async = data;
659 if (async->isolate_sigpipe) {
662 sigaddset(&mask, SIGPIPE);
663 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
664 ret = error("unable to block SIGPIPE in async thread");
669 pthread_setspecific(async_key, async);
670 ret = async->proc(async->proc_in, async->proc_out, async->data);
674 static NORETURN void die_async(const char *err, va_list params)
676 vreportf("fatal: ", err, params);
679 struct async *async = pthread_getspecific(async_key);
680 if (async->proc_in >= 0)
681 close(async->proc_in);
682 if (async->proc_out >= 0)
683 close(async->proc_out);
684 pthread_exit((void *)128);
690 static int async_die_is_recursing(void)
692 void *ret = pthread_getspecific(async_die_counter);
693 pthread_setspecific(async_die_counter, (void *)1);
699 if (!main_thread_set)
700 return 0; /* no asyncs started yet */
701 return !pthread_equal(main_thread, pthread_self());
704 static void NORETURN async_exit(int code)
706 pthread_exit((void *)(intptr_t)code);
712 void (**handlers)(void);
717 static int git_atexit_installed;
719 static void git_atexit_dispatch(void)
723 for (i=git_atexit_hdlrs.nr ; i ; i--)
724 git_atexit_hdlrs.handlers[i-1]();
727 static void git_atexit_clear(void)
729 free(git_atexit_hdlrs.handlers);
730 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
731 git_atexit_installed = 0;
735 int git_atexit(void (*handler)(void))
737 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
738 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
739 if (!git_atexit_installed) {
740 if (atexit(&git_atexit_dispatch))
742 git_atexit_installed = 1;
746 #define atexit git_atexit
748 static int process_is_async;
751 return process_is_async;
754 static void NORETURN async_exit(int code)
761 void check_pipe(int err)
767 signal(SIGPIPE, SIG_DFL);
769 /* Should never happen, but just in case... */
774 int start_async(struct async *async)
776 int need_in, need_out;
777 int fdin[2], fdout[2];
778 int proc_in, proc_out;
780 need_in = async->in < 0;
782 if (pipe(fdin) < 0) {
785 return error_errno("cannot create pipe");
790 need_out = async->out < 0;
792 if (pipe(fdout) < 0) {
797 return error_errno("cannot create pipe");
799 async->out = fdout[0];
812 proc_out = async->out;
817 /* Flush stdio before fork() to avoid cloning buffers */
821 if (async->pid < 0) {
822 error_errno("fork (async) failed");
831 process_is_async = 1;
832 exit(!!async->proc(proc_in, proc_out, async->data));
835 mark_child_for_cleanup(async->pid, NULL);
847 if (!main_thread_set) {
849 * We assume that the first time that start_async is called
850 * it is from the main thread.
853 main_thread = pthread_self();
854 pthread_key_create(&async_key, NULL);
855 pthread_key_create(&async_die_counter, NULL);
856 set_die_routine(die_async);
857 set_die_is_recursing_routine(async_die_is_recursing);
861 set_cloexec(proc_in);
863 set_cloexec(proc_out);
864 async->proc_in = proc_in;
865 async->proc_out = proc_out;
867 int err = pthread_create(&async->tid, NULL, run_thread, async);
869 error_errno("cannot create thread");
889 int finish_async(struct async *async)
892 return wait_or_whine(async->pid, "child process", 0);
894 void *ret = (void *)(intptr_t)(-1);
896 if (pthread_join(async->tid, &ret))
897 error("pthread_join failed");
898 return (int)(intptr_t)ret;
902 const char *find_hook(const char *name)
904 static struct strbuf path = STRBUF_INIT;
907 strbuf_git_path(&path, "hooks/%s", name);
908 if (access(path.buf, X_OK) < 0) {
909 #ifdef STRIP_EXTENSION
910 strbuf_addstr(&path, STRIP_EXTENSION);
911 if (access(path.buf, X_OK) >= 0)
919 int run_hook_ve(const char *const *env, const char *name, va_list args)
921 struct child_process hook = CHILD_PROCESS_INIT;
928 argv_array_push(&hook.args, p);
929 while ((p = va_arg(args, const char *)))
930 argv_array_push(&hook.args, p);
933 hook.stdout_to_stderr = 1;
935 return run_command(&hook);
938 int run_hook_le(const char *const *env, const char *name, ...)
943 va_start(args, name);
944 ret = run_hook_ve(env, name, args);
951 /* initialized by caller */
953 int type; /* POLLOUT or POLLIN */
965 /* returned by pump_io */
966 int error; /* 0 for success, otherwise errno */
972 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
977 for (i = 0; i < nr; i++) {
978 struct io_pump *io = &slots[i];
981 pfd[pollsize].fd = io->fd;
982 pfd[pollsize].events = io->type;
983 io->pfd = &pfd[pollsize++];
989 if (poll(pfd, pollsize, -1) < 0) {
992 die_errno("poll failed");
995 for (i = 0; i < nr; i++) {
996 struct io_pump *io = &slots[i];
1001 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1004 if (io->type == POLLOUT) {
1005 ssize_t len = xwrite(io->fd,
1006 io->u.out.buf, io->u.out.len);
1012 io->u.out.buf += len;
1013 io->u.out.len -= len;
1014 if (!io->u.out.len) {
1021 if (io->type == POLLIN) {
1022 ssize_t len = strbuf_read_once(io->u.in.buf,
1023 io->fd, io->u.in.hint);
1036 static int pump_io(struct io_pump *slots, int nr)
1041 for (i = 0; i < nr; i++)
1044 ALLOC_ARRAY(pfd, nr);
1045 while (pump_io_round(slots, nr, pfd))
1049 /* There may be multiple errno values, so just pick the first. */
1050 for (i = 0; i < nr; i++) {
1051 if (slots[i].error) {
1052 errno = slots[i].error;
1060 int pipe_command(struct child_process *cmd,
1061 const char *in, size_t in_len,
1062 struct strbuf *out, size_t out_hint,
1063 struct strbuf *err, size_t err_hint)
1065 struct io_pump io[3];
1075 if (start_command(cmd) < 0)
1079 io[nr].fd = cmd->in;
1080 io[nr].type = POLLOUT;
1081 io[nr].u.out.buf = in;
1082 io[nr].u.out.len = in_len;
1086 io[nr].fd = cmd->out;
1087 io[nr].type = POLLIN;
1088 io[nr].u.in.buf = out;
1089 io[nr].u.in.hint = out_hint;
1093 io[nr].fd = cmd->err;
1094 io[nr].type = POLLIN;
1095 io[nr].u.in.buf = err;
1096 io[nr].u.in.hint = err_hint;
1100 if (pump_io(io, nr) < 0) {
1101 finish_command(cmd); /* throw away exit code */
1105 return finish_command(cmd);
1111 GIT_CP_WAIT_CLEANUP,
1114 struct parallel_processes {
1120 get_next_task_fn get_next_task;
1121 start_failure_fn start_failure;
1122 task_finished_fn task_finished;
1125 enum child_state state;
1126 struct child_process process;
1131 * The struct pollfd is logically part of *children,
1132 * but the system call expects it as its own array.
1136 unsigned shutdown : 1;
1139 struct strbuf buffered_output; /* of finished children */
1142 static int default_start_failure(struct strbuf *out,
1149 static int default_task_finished(int result,
1157 static void kill_children(struct parallel_processes *pp, int signo)
1159 int i, n = pp->max_processes;
1161 for (i = 0; i < n; i++)
1162 if (pp->children[i].state == GIT_CP_WORKING)
1163 kill(pp->children[i].process.pid, signo);
1166 static struct parallel_processes *pp_for_signal;
1168 static void handle_children_on_signal(int signo)
1170 kill_children(pp_for_signal, signo);
1171 sigchain_pop(signo);
1175 static void pp_init(struct parallel_processes *pp,
1177 get_next_task_fn get_next_task,
1178 start_failure_fn start_failure,
1179 task_finished_fn task_finished,
1187 pp->max_processes = n;
1189 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1193 die("BUG: you need to specify a get_next_task function");
1194 pp->get_next_task = get_next_task;
1196 pp->start_failure = start_failure ? start_failure : default_start_failure;
1197 pp->task_finished = task_finished ? task_finished : default_task_finished;
1199 pp->nr_processes = 0;
1200 pp->output_owner = 0;
1202 pp->children = xcalloc(n, sizeof(*pp->children));
1203 pp->pfd = xcalloc(n, sizeof(*pp->pfd));
1204 strbuf_init(&pp->buffered_output, 0);
1206 for (i = 0; i < n; i++) {
1207 strbuf_init(&pp->children[i].err, 0);
1208 child_process_init(&pp->children[i].process);
1209 pp->pfd[i].events = POLLIN | POLLHUP;
1214 sigchain_push_common(handle_children_on_signal);
1217 static void pp_cleanup(struct parallel_processes *pp)
1221 trace_printf("run_processes_parallel: done");
1222 for (i = 0; i < pp->max_processes; i++) {
1223 strbuf_release(&pp->children[i].err);
1224 child_process_clear(&pp->children[i].process);
1231 * When get_next_task added messages to the buffer in its last
1232 * iteration, the buffered output is non empty.
1234 strbuf_write(&pp->buffered_output, stderr);
1235 strbuf_release(&pp->buffered_output);
1237 sigchain_pop_common();
1241 * 0 if a new task was started.
1242 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1243 * problem with starting a new command)
1244 * <0 no new job was started, user wishes to shutdown early. Use negative code
1245 * to signal the children.
1247 static int pp_start_one(struct parallel_processes *pp)
1251 for (i = 0; i < pp->max_processes; i++)
1252 if (pp->children[i].state == GIT_CP_FREE)
1254 if (i == pp->max_processes)
1255 die("BUG: bookkeeping is hard");
1257 code = pp->get_next_task(&pp->children[i].process,
1258 &pp->children[i].err,
1260 &pp->children[i].data);
1262 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1263 strbuf_reset(&pp->children[i].err);
1266 pp->children[i].process.err = -1;
1267 pp->children[i].process.stdout_to_stderr = 1;
1268 pp->children[i].process.no_stdin = 1;
1270 if (start_command(&pp->children[i].process)) {
1271 code = pp->start_failure(&pp->children[i].err,
1273 &pp->children[i].data);
1274 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1275 strbuf_reset(&pp->children[i].err);
1282 pp->children[i].state = GIT_CP_WORKING;
1283 pp->pfd[i].fd = pp->children[i].process.err;
1287 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1291 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1298 /* Buffer output from all pipes. */
1299 for (i = 0; i < pp->max_processes; i++) {
1300 if (pp->children[i].state == GIT_CP_WORKING &&
1301 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1302 int n = strbuf_read_once(&pp->children[i].err,
1303 pp->children[i].process.err, 0);
1305 close(pp->children[i].process.err);
1306 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1308 if (errno != EAGAIN)
1314 static void pp_output(struct parallel_processes *pp)
1316 int i = pp->output_owner;
1317 if (pp->children[i].state == GIT_CP_WORKING &&
1318 pp->children[i].err.len) {
1319 strbuf_write(&pp->children[i].err, stderr);
1320 strbuf_reset(&pp->children[i].err);
1324 static int pp_collect_finished(struct parallel_processes *pp)
1327 int n = pp->max_processes;
1330 while (pp->nr_processes > 0) {
1331 for (i = 0; i < pp->max_processes; i++)
1332 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1334 if (i == pp->max_processes)
1337 code = finish_command(&pp->children[i].process);
1339 code = pp->task_finished(code,
1340 &pp->children[i].err, pp->data,
1341 &pp->children[i].data);
1349 pp->children[i].state = GIT_CP_FREE;
1351 child_process_init(&pp->children[i].process);
1353 if (i != pp->output_owner) {
1354 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1355 strbuf_reset(&pp->children[i].err);
1357 strbuf_write(&pp->children[i].err, stderr);
1358 strbuf_reset(&pp->children[i].err);
1360 /* Output all other finished child processes */
1361 strbuf_write(&pp->buffered_output, stderr);
1362 strbuf_reset(&pp->buffered_output);
1365 * Pick next process to output live.
1367 * For now we pick it randomly by doing a round
1368 * robin. Later we may want to pick the one with
1369 * the most output or the longest or shortest
1370 * running process time.
1372 for (i = 0; i < n; i++)
1373 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1375 pp->output_owner = (pp->output_owner + i) % n;
1381 int run_processes_parallel(int n,
1382 get_next_task_fn get_next_task,
1383 start_failure_fn start_failure,
1384 task_finished_fn task_finished,
1388 int output_timeout = 100;
1390 struct parallel_processes pp;
1392 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1395 i < spawn_cap && !pp.shutdown &&
1396 pp.nr_processes < pp.max_processes;
1398 code = pp_start_one(&pp);
1403 kill_children(&pp, -code);
1407 if (!pp.nr_processes)
1409 pp_buffer_stderr(&pp, output_timeout);
1411 code = pp_collect_finished(&pp);
1415 kill_children(&pp, -code);