X-Git-Url: https://git.tokkee.org/?a=blobdiff_plain;f=run-command.c;h=7068ec7e6d74af0cec233259b4b6e41a61ed5123;hb=c30e699fc509f43f459c17d3148e7d866fb9157a;hp=476d00c2182e3af82a0cfe495c61c9df1eb44d26;hpb=50f3ac29cbadbf7e0ff099b493b00cfa4129e1e0;p=git.git diff --git a/run-command.c b/run-command.c index 476d00c21..7068ec7e6 100644 --- a/run-command.c +++ b/run-command.c @@ -20,12 +20,19 @@ int start_command(struct child_process *cmd) int need_in, need_out, need_err; int fdin[2], fdout[2], fderr[2]; + /* + * In case of errors we must keep the promise to close FDs + * that have been passed in via ->in and ->out. + */ + need_in = !cmd->no_stdin && cmd->in < 0; if (need_in) { - if (pipe(fdin) < 0) + if (pipe(fdin) < 0) { + if (cmd->out > 0) + close(cmd->out); return -ERR_RUN_COMMAND_PIPE; + } cmd->in = fdin[1]; - cmd->close_in = 1; } need_out = !cmd->no_stdout @@ -35,10 +42,11 @@ int start_command(struct child_process *cmd) if (pipe(fdout) < 0) { if (need_in) close_pair(fdin); + else if (cmd->in) + close(cmd->in); return -ERR_RUN_COMMAND_PIPE; } cmd->out = fdout[0]; - cmd->close_out = 1; } need_err = !cmd->no_stderr && cmd->err < 0; @@ -46,19 +54,29 @@ int start_command(struct child_process *cmd) if (pipe(fderr) < 0) { if (need_in) close_pair(fdin); + else if (cmd->in) + close(cmd->in); if (need_out) close_pair(fdout); + else if (cmd->out) + close(cmd->out); return -ERR_RUN_COMMAND_PIPE; } cmd->err = fderr[0]; } + trace_argv_printf(cmd->argv, "trace: run_command:"); + cmd->pid = fork(); if (cmd->pid < 0) { if (need_in) close_pair(fdin); + else if (cmd->in) + close(cmd->in); if (need_out) close_pair(fdout); + else if (cmd->out) + close(cmd->out); if (need_err) close_pair(fderr); return -ERR_RUN_COMMAND_FORK; @@ -75,6 +93,13 @@ int start_command(struct child_process *cmd) close(cmd->in); } + if (cmd->no_stderr) + dup_devnull(2); + else if (need_err) { + dup2(fderr[1], 2); + close_pair(fderr); + } + if (cmd->no_stdout) dup_devnull(1); else if (cmd->stdout_to_stderr) @@ -87,13 +112,6 @@ int start_command(struct child_process *cmd) close(cmd->out); } - if (cmd->no_stderr) - dup_devnull(2); - else if (need_err) { - dup2(fderr[1], 2); - close_pair(fderr); - } - if (cmd->dir && chdir(cmd->dir)) die("exec %s: cd to %s failed (%s)", cmd->argv[0], cmd->dir, strerror(errno)); @@ -120,7 +138,7 @@ int start_command(struct child_process *cmd) if (need_out) close(fdout[1]); - else if (cmd->out > 1) + else if (cmd->out) close(cmd->out); if (need_err) @@ -157,10 +175,6 @@ static int wait_or_whine(pid_t pid) int finish_command(struct child_process *cmd) { - if (cmd->close_in) - close(cmd->in); - if (cmd->close_out) - close(cmd->out); return wait_or_whine(cmd->pid); }