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;
214 static void notify_parent(void)
217 * execvp failed. If possible, we'd like to let start_command
218 * know, so failures like ENOENT can be handled right away; but
219 * otherwise, finish_command will still report the error.
221 xwrite(child_notifier, "", 1);
224 static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
227 die("BUG: command is empty");
230 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
231 * attempt to interpret the command with 'sh'.
233 argv_array_push(out, SHELL_PATH);
236 argv_array_push(out, "git");
237 argv_array_pushv(out, cmd->argv);
238 } else if (cmd->use_shell) {
239 prepare_shell_cmd(out, cmd->argv);
241 argv_array_pushv(out, cmd->argv);
245 * If there are no '/' characters in the command then perform a path
246 * lookup and use the resolved path as the command to exec. If there
247 * are no '/' characters or if the command wasn't found in the path,
248 * have exec attempt to invoke the command directly.
250 if (!strchr(out->argv[1], '/')) {
251 char *program = locate_in_PATH(out->argv[1]);
253 free((char *)out->argv[1]);
254 out->argv[1] = program;
259 static char **prep_childenv(const char *const *deltaenv)
261 extern char **environ;
263 struct string_list env = STRING_LIST_INIT_DUP;
264 struct strbuf key = STRBUF_INIT;
265 const char *const *p;
268 /* Construct a sorted string list consisting of the current environ */
269 for (p = (const char *const *) environ; p && *p; p++) {
270 const char *equals = strchr(*p, '=');
274 strbuf_add(&key, *p, equals - *p);
275 string_list_append(&env, key.buf)->util = (void *) *p;
277 string_list_append(&env, *p)->util = (void *) *p;
280 string_list_sort(&env);
282 /* Merge in 'deltaenv' with the current environ */
283 for (p = deltaenv; p && *p; p++) {
284 const char *equals = strchr(*p, '=');
287 /* ('key=value'), insert or replace entry */
289 strbuf_add(&key, *p, equals - *p);
290 string_list_insert(&env, key.buf)->util = (void *) *p;
292 /* otherwise ('key') remove existing entry */
293 string_list_remove(&env, *p, 0);
297 /* Create an array of 'char *' to be used as the childenv */
298 childenv = xmalloc((env.nr + 1) * sizeof(char *));
299 for (i = 0; i < env.nr; i++)
300 childenv[i] = env.items[i].util;
301 childenv[env.nr] = NULL;
303 string_list_clear(&env, 0);
304 strbuf_release(&key);
309 static inline void set_cloexec(int fd)
311 int flags = fcntl(fd, F_GETFD);
313 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
316 static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
318 int status, code = -1;
320 int failed_errno = 0;
322 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
328 failed_errno = errno;
329 error_errno("waitpid for %s failed", argv0);
330 } else if (waiting != pid) {
331 error("waitpid is confused (%s)", argv0);
332 } else if (WIFSIGNALED(status)) {
333 code = WTERMSIG(status);
334 if (code != SIGINT && code != SIGQUIT && code != SIGPIPE)
335 error("%s died of signal %d", argv0, code);
337 * This return value is chosen so that code & 0xff
338 * mimics the exit code that a POSIX shell would report for
339 * a program that died from this signal.
342 } else if (WIFEXITED(status)) {
343 code = WEXITSTATUS(status);
345 * Convert special exit code when execvp failed.
349 failed_errno = ENOENT;
352 error("waitpid is confused (%s)", argv0);
355 clear_child_for_cleanup(pid);
357 errno = failed_errno;
361 int start_command(struct child_process *cmd)
363 int need_in, need_out, need_err;
364 int fdin[2], fdout[2], fderr[2];
369 cmd->argv = cmd->args.argv;
371 cmd->env = cmd->env_array.argv;
374 * In case of errors we must keep the promise to close FDs
375 * that have been passed in via ->in and ->out.
378 need_in = !cmd->no_stdin && cmd->in < 0;
380 if (pipe(fdin) < 0) {
381 failed_errno = errno;
384 str = "standard input";
390 need_out = !cmd->no_stdout
391 && !cmd->stdout_to_stderr
394 if (pipe(fdout) < 0) {
395 failed_errno = errno;
400 str = "standard output";
406 need_err = !cmd->no_stderr && cmd->err < 0;
408 if (pipe(fderr) < 0) {
409 failed_errno = errno;
418 str = "standard error";
420 error("cannot create %s pipe for %s: %s",
421 str, cmd->argv[0], strerror(failed_errno));
422 child_process_clear(cmd);
423 errno = failed_errno;
429 trace_argv_printf(cmd->argv, "trace: run_command:");
432 #ifndef GIT_WINDOWS_NATIVE
437 struct argv_array argv = ARGV_ARRAY_INIT;
439 if (pipe(notify_pipe))
440 notify_pipe[0] = notify_pipe[1] = -1;
442 if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
443 null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);
445 die_errno(_("open /dev/null failed"));
446 set_cloexec(null_fd);
449 prepare_cmd(&argv, cmd);
450 childenv = prep_childenv(cmd->env);
453 failed_errno = errno;
456 * Redirect the channel to write syscall error messages to
457 * before redirecting the process's stderr so that all die()
458 * in subsequent call paths use the parent's stderr.
460 if (cmd->no_stderr || need_err) {
461 int child_err = dup(2);
462 set_cloexec(child_err);
463 set_error_handle(fdopen(child_err, "w"));
466 close(notify_pipe[0]);
467 set_cloexec(notify_pipe[1]);
468 child_notifier = notify_pipe[1];
469 atexit(notify_parent);
476 } else if (cmd->in) {
486 } else if (cmd->err > 1) {
493 else if (cmd->stdout_to_stderr)
498 } else if (cmd->out > 1) {
503 if (cmd->dir && chdir(cmd->dir))
504 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
508 * Attempt to exec using the command and arguments starting at
509 * argv.argv[1]. argv.argv[0] contains SHELL_PATH which will
510 * be used in the event exec failed with ENOEXEC at which point
511 * we will try to interpret the command using 'sh'.
513 execve(argv.argv[1], (char *const *) argv.argv + 1,
514 (char *const *) childenv);
515 if (errno == ENOEXEC)
516 execve(argv.argv[0], (char *const *) argv.argv,
517 (char *const *) childenv);
519 if (errno == ENOENT) {
520 if (!cmd->silent_exec_failure)
521 error("cannot run %s: %s", cmd->argv[0],
525 die_errno("cannot exec '%s'", cmd->argv[0]);
529 error_errno("cannot fork() for %s", cmd->argv[0]);
530 else if (cmd->clean_on_exit)
531 mark_child_for_cleanup(cmd->pid, cmd);
534 * Wait for child's exec. If the exec succeeds (or if fork()
535 * failed), EOF is seen immediately by the parent. Otherwise, the
536 * child process sends a single byte.
537 * Note that use of this infrastructure is completely advisory,
538 * therefore, we keep error checks minimal.
540 close(notify_pipe[1]);
541 if (read(notify_pipe[0], ¬ify_pipe[1], 1) == 1) {
543 * At this point we know that fork() succeeded, but exec()
544 * failed. Errors have been reported to our stderr.
546 wait_or_whine(cmd->pid, cmd->argv[0], 0);
547 failed_errno = errno;
550 close(notify_pipe[0]);
554 argv_array_clear(&argv);
559 int fhin = 0, fhout = 1, fherr = 2;
560 const char **sargv = cmd->argv;
561 struct argv_array nargv = ARGV_ARRAY_INIT;
564 fhin = open("/dev/null", O_RDWR);
571 fherr = open("/dev/null", O_RDWR);
573 fherr = dup(fderr[1]);
574 else if (cmd->err > 2)
575 fherr = dup(cmd->err);
578 fhout = open("/dev/null", O_RDWR);
579 else if (cmd->stdout_to_stderr)
582 fhout = dup(fdout[1]);
583 else if (cmd->out > 1)
584 fhout = dup(cmd->out);
587 cmd->argv = prepare_git_cmd(&nargv, cmd->argv);
588 else if (cmd->use_shell)
589 cmd->argv = prepare_shell_cmd(&nargv, cmd->argv);
591 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, (char**) cmd->env,
592 cmd->dir, fhin, fhout, fherr);
593 failed_errno = errno;
594 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
595 error_errno("cannot spawn %s", cmd->argv[0]);
596 if (cmd->clean_on_exit && cmd->pid >= 0)
597 mark_child_for_cleanup(cmd->pid, cmd);
599 argv_array_clear(&nargv);
623 child_process_clear(cmd);
624 errno = failed_errno;
646 int finish_command(struct child_process *cmd)
648 int ret = wait_or_whine(cmd->pid, cmd->argv[0], 0);
649 child_process_clear(cmd);
653 int finish_command_in_signal(struct child_process *cmd)
655 return wait_or_whine(cmd->pid, cmd->argv[0], 1);
659 int run_command(struct child_process *cmd)
663 if (cmd->out < 0 || cmd->err < 0)
664 die("BUG: run_command with a pipe can cause deadlock");
666 code = start_command(cmd);
669 return finish_command(cmd);
672 int run_command_v_opt(const char **argv, int opt)
674 return run_command_v_opt_cd_env(argv, opt, NULL, NULL);
677 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
679 struct child_process cmd = CHILD_PROCESS_INIT;
681 cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
682 cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
683 cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
684 cmd.silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
685 cmd.use_shell = opt & RUN_USING_SHELL ? 1 : 0;
686 cmd.clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
689 return run_command(&cmd);
693 static pthread_t main_thread;
694 static int main_thread_set;
695 static pthread_key_t async_key;
696 static pthread_key_t async_die_counter;
698 static void *run_thread(void *data)
700 struct async *async = data;
703 if (async->isolate_sigpipe) {
706 sigaddset(&mask, SIGPIPE);
707 if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) {
708 ret = error("unable to block SIGPIPE in async thread");
713 pthread_setspecific(async_key, async);
714 ret = async->proc(async->proc_in, async->proc_out, async->data);
718 static NORETURN void die_async(const char *err, va_list params)
720 vreportf("fatal: ", err, params);
723 struct async *async = pthread_getspecific(async_key);
724 if (async->proc_in >= 0)
725 close(async->proc_in);
726 if (async->proc_out >= 0)
727 close(async->proc_out);
728 pthread_exit((void *)128);
734 static int async_die_is_recursing(void)
736 void *ret = pthread_getspecific(async_die_counter);
737 pthread_setspecific(async_die_counter, (void *)1);
743 if (!main_thread_set)
744 return 0; /* no asyncs started yet */
745 return !pthread_equal(main_thread, pthread_self());
748 static void NORETURN async_exit(int code)
750 pthread_exit((void *)(intptr_t)code);
756 void (**handlers)(void);
761 static int git_atexit_installed;
763 static void git_atexit_dispatch(void)
767 for (i=git_atexit_hdlrs.nr ; i ; i--)
768 git_atexit_hdlrs.handlers[i-1]();
771 static void git_atexit_clear(void)
773 free(git_atexit_hdlrs.handlers);
774 memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
775 git_atexit_installed = 0;
779 int git_atexit(void (*handler)(void))
781 ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
782 git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
783 if (!git_atexit_installed) {
784 if (atexit(&git_atexit_dispatch))
786 git_atexit_installed = 1;
790 #define atexit git_atexit
792 static int process_is_async;
795 return process_is_async;
798 static void NORETURN async_exit(int code)
805 void check_pipe(int err)
811 signal(SIGPIPE, SIG_DFL);
813 /* Should never happen, but just in case... */
818 int start_async(struct async *async)
820 int need_in, need_out;
821 int fdin[2], fdout[2];
822 int proc_in, proc_out;
824 need_in = async->in < 0;
826 if (pipe(fdin) < 0) {
829 return error_errno("cannot create pipe");
834 need_out = async->out < 0;
836 if (pipe(fdout) < 0) {
841 return error_errno("cannot create pipe");
843 async->out = fdout[0];
856 proc_out = async->out;
861 /* Flush stdio before fork() to avoid cloning buffers */
865 if (async->pid < 0) {
866 error_errno("fork (async) failed");
875 process_is_async = 1;
876 exit(!!async->proc(proc_in, proc_out, async->data));
879 mark_child_for_cleanup(async->pid, NULL);
891 if (!main_thread_set) {
893 * We assume that the first time that start_async is called
894 * it is from the main thread.
897 main_thread = pthread_self();
898 pthread_key_create(&async_key, NULL);
899 pthread_key_create(&async_die_counter, NULL);
900 set_die_routine(die_async);
901 set_die_is_recursing_routine(async_die_is_recursing);
905 set_cloexec(proc_in);
907 set_cloexec(proc_out);
908 async->proc_in = proc_in;
909 async->proc_out = proc_out;
911 int err = pthread_create(&async->tid, NULL, run_thread, async);
913 error_errno("cannot create thread");
933 int finish_async(struct async *async)
936 return wait_or_whine(async->pid, "child process", 0);
938 void *ret = (void *)(intptr_t)(-1);
940 if (pthread_join(async->tid, &ret))
941 error("pthread_join failed");
942 return (int)(intptr_t)ret;
946 const char *find_hook(const char *name)
948 static struct strbuf path = STRBUF_INIT;
951 strbuf_git_path(&path, "hooks/%s", name);
952 if (access(path.buf, X_OK) < 0) {
953 #ifdef STRIP_EXTENSION
954 strbuf_addstr(&path, STRIP_EXTENSION);
955 if (access(path.buf, X_OK) >= 0)
963 int run_hook_ve(const char *const *env, const char *name, va_list args)
965 struct child_process hook = CHILD_PROCESS_INIT;
972 argv_array_push(&hook.args, p);
973 while ((p = va_arg(args, const char *)))
974 argv_array_push(&hook.args, p);
977 hook.stdout_to_stderr = 1;
979 return run_command(&hook);
982 int run_hook_le(const char *const *env, const char *name, ...)
987 va_start(args, name);
988 ret = run_hook_ve(env, name, args);
995 /* initialized by caller */
997 int type; /* POLLOUT or POLLIN */
1009 /* returned by pump_io */
1010 int error; /* 0 for success, otherwise errno */
1016 static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1021 for (i = 0; i < nr; i++) {
1022 struct io_pump *io = &slots[i];
1025 pfd[pollsize].fd = io->fd;
1026 pfd[pollsize].events = io->type;
1027 io->pfd = &pfd[pollsize++];
1033 if (poll(pfd, pollsize, -1) < 0) {
1036 die_errno("poll failed");
1039 for (i = 0; i < nr; i++) {
1040 struct io_pump *io = &slots[i];
1045 if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1048 if (io->type == POLLOUT) {
1049 ssize_t len = xwrite(io->fd,
1050 io->u.out.buf, io->u.out.len);
1056 io->u.out.buf += len;
1057 io->u.out.len -= len;
1058 if (!io->u.out.len) {
1065 if (io->type == POLLIN) {
1066 ssize_t len = strbuf_read_once(io->u.in.buf,
1067 io->fd, io->u.in.hint);
1080 static int pump_io(struct io_pump *slots, int nr)
1085 for (i = 0; i < nr; i++)
1088 ALLOC_ARRAY(pfd, nr);
1089 while (pump_io_round(slots, nr, pfd))
1093 /* There may be multiple errno values, so just pick the first. */
1094 for (i = 0; i < nr; i++) {
1095 if (slots[i].error) {
1096 errno = slots[i].error;
1104 int pipe_command(struct child_process *cmd,
1105 const char *in, size_t in_len,
1106 struct strbuf *out, size_t out_hint,
1107 struct strbuf *err, size_t err_hint)
1109 struct io_pump io[3];
1119 if (start_command(cmd) < 0)
1123 io[nr].fd = cmd->in;
1124 io[nr].type = POLLOUT;
1125 io[nr].u.out.buf = in;
1126 io[nr].u.out.len = in_len;
1130 io[nr].fd = cmd->out;
1131 io[nr].type = POLLIN;
1132 io[nr].u.in.buf = out;
1133 io[nr].u.in.hint = out_hint;
1137 io[nr].fd = cmd->err;
1138 io[nr].type = POLLIN;
1139 io[nr].u.in.buf = err;
1140 io[nr].u.in.hint = err_hint;
1144 if (pump_io(io, nr) < 0) {
1145 finish_command(cmd); /* throw away exit code */
1149 return finish_command(cmd);
1155 GIT_CP_WAIT_CLEANUP,
1158 struct parallel_processes {
1164 get_next_task_fn get_next_task;
1165 start_failure_fn start_failure;
1166 task_finished_fn task_finished;
1169 enum child_state state;
1170 struct child_process process;
1175 * The struct pollfd is logically part of *children,
1176 * but the system call expects it as its own array.
1180 unsigned shutdown : 1;
1183 struct strbuf buffered_output; /* of finished children */
1186 static int default_start_failure(struct strbuf *out,
1193 static int default_task_finished(int result,
1201 static void kill_children(struct parallel_processes *pp, int signo)
1203 int i, n = pp->max_processes;
1205 for (i = 0; i < n; i++)
1206 if (pp->children[i].state == GIT_CP_WORKING)
1207 kill(pp->children[i].process.pid, signo);
1210 static struct parallel_processes *pp_for_signal;
1212 static void handle_children_on_signal(int signo)
1214 kill_children(pp_for_signal, signo);
1215 sigchain_pop(signo);
1219 static void pp_init(struct parallel_processes *pp,
1221 get_next_task_fn get_next_task,
1222 start_failure_fn start_failure,
1223 task_finished_fn task_finished,
1231 pp->max_processes = n;
1233 trace_printf("run_processes_parallel: preparing to run up to %d tasks", n);
1237 die("BUG: you need to specify a get_next_task function");
1238 pp->get_next_task = get_next_task;
1240 pp->start_failure = start_failure ? start_failure : default_start_failure;
1241 pp->task_finished = task_finished ? task_finished : default_task_finished;
1243 pp->nr_processes = 0;
1244 pp->output_owner = 0;
1246 pp->children = xcalloc(n, sizeof(*pp->children));
1247 pp->pfd = xcalloc(n, sizeof(*pp->pfd));
1248 strbuf_init(&pp->buffered_output, 0);
1250 for (i = 0; i < n; i++) {
1251 strbuf_init(&pp->children[i].err, 0);
1252 child_process_init(&pp->children[i].process);
1253 pp->pfd[i].events = POLLIN | POLLHUP;
1258 sigchain_push_common(handle_children_on_signal);
1261 static void pp_cleanup(struct parallel_processes *pp)
1265 trace_printf("run_processes_parallel: done");
1266 for (i = 0; i < pp->max_processes; i++) {
1267 strbuf_release(&pp->children[i].err);
1268 child_process_clear(&pp->children[i].process);
1275 * When get_next_task added messages to the buffer in its last
1276 * iteration, the buffered output is non empty.
1278 strbuf_write(&pp->buffered_output, stderr);
1279 strbuf_release(&pp->buffered_output);
1281 sigchain_pop_common();
1285 * 0 if a new task was started.
1286 * 1 if no new jobs was started (get_next_task ran out of work, non critical
1287 * problem with starting a new command)
1288 * <0 no new job was started, user wishes to shutdown early. Use negative code
1289 * to signal the children.
1291 static int pp_start_one(struct parallel_processes *pp)
1295 for (i = 0; i < pp->max_processes; i++)
1296 if (pp->children[i].state == GIT_CP_FREE)
1298 if (i == pp->max_processes)
1299 die("BUG: bookkeeping is hard");
1301 code = pp->get_next_task(&pp->children[i].process,
1302 &pp->children[i].err,
1304 &pp->children[i].data);
1306 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1307 strbuf_reset(&pp->children[i].err);
1310 pp->children[i].process.err = -1;
1311 pp->children[i].process.stdout_to_stderr = 1;
1312 pp->children[i].process.no_stdin = 1;
1314 if (start_command(&pp->children[i].process)) {
1315 code = pp->start_failure(&pp->children[i].err,
1317 &pp->children[i].data);
1318 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1319 strbuf_reset(&pp->children[i].err);
1326 pp->children[i].state = GIT_CP_WORKING;
1327 pp->pfd[i].fd = pp->children[i].process.err;
1331 static void pp_buffer_stderr(struct parallel_processes *pp, int output_timeout)
1335 while ((i = poll(pp->pfd, pp->max_processes, output_timeout)) < 0) {
1342 /* Buffer output from all pipes. */
1343 for (i = 0; i < pp->max_processes; i++) {
1344 if (pp->children[i].state == GIT_CP_WORKING &&
1345 pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1346 int n = strbuf_read_once(&pp->children[i].err,
1347 pp->children[i].process.err, 0);
1349 close(pp->children[i].process.err);
1350 pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1352 if (errno != EAGAIN)
1358 static void pp_output(struct parallel_processes *pp)
1360 int i = pp->output_owner;
1361 if (pp->children[i].state == GIT_CP_WORKING &&
1362 pp->children[i].err.len) {
1363 strbuf_write(&pp->children[i].err, stderr);
1364 strbuf_reset(&pp->children[i].err);
1368 static int pp_collect_finished(struct parallel_processes *pp)
1371 int n = pp->max_processes;
1374 while (pp->nr_processes > 0) {
1375 for (i = 0; i < pp->max_processes; i++)
1376 if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1378 if (i == pp->max_processes)
1381 code = finish_command(&pp->children[i].process);
1383 code = pp->task_finished(code,
1384 &pp->children[i].err, pp->data,
1385 &pp->children[i].data);
1393 pp->children[i].state = GIT_CP_FREE;
1395 child_process_init(&pp->children[i].process);
1397 if (i != pp->output_owner) {
1398 strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1399 strbuf_reset(&pp->children[i].err);
1401 strbuf_write(&pp->children[i].err, stderr);
1402 strbuf_reset(&pp->children[i].err);
1404 /* Output all other finished child processes */
1405 strbuf_write(&pp->buffered_output, stderr);
1406 strbuf_reset(&pp->buffered_output);
1409 * Pick next process to output live.
1411 * For now we pick it randomly by doing a round
1412 * robin. Later we may want to pick the one with
1413 * the most output or the longest or shortest
1414 * running process time.
1416 for (i = 0; i < n; i++)
1417 if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1419 pp->output_owner = (pp->output_owner + i) % n;
1425 int run_processes_parallel(int n,
1426 get_next_task_fn get_next_task,
1427 start_failure_fn start_failure,
1428 task_finished_fn task_finished,
1432 int output_timeout = 100;
1434 struct parallel_processes pp;
1436 pp_init(&pp, n, get_next_task, start_failure, task_finished, pp_cb);
1439 i < spawn_cap && !pp.shutdown &&
1440 pp.nr_processes < pp.max_processes;
1442 code = pp_start_one(&pp);
1447 kill_children(&pp, -code);
1451 if (!pp.nr_processes)
1453 pp_buffer_stderr(&pp, output_timeout);
1455 code = pp_collect_finished(&pp);
1459 kill_children(&pp, -code);