| 675 | } |
| 676 | |
| 677 | int start_command(struct child_process *cmd) |
| 678 | { |
| 679 | int need_in, need_out, need_err; |
| 680 | int fdin[2], fdout[2], fderr[2]; |
| 681 | int failed_errno; |
| 682 | const char *str; |
| 683 | |
| 684 | /* |
| 685 | * In case of errors we must keep the promise to close FDs |
| 686 | * that have been passed in via ->in and ->out. |
| 687 | */ |
| 688 | |
| 689 | need_in = !cmd->no_stdin && cmd->in < 0; |
| 690 | if (need_in) { |
| 691 | if (pipe(fdin) < 0) { |
| 692 | failed_errno = errno; |
| 693 | if (cmd->out > 0) |
| 694 | close(cmd->out); |
| 695 | str = "standard input"; |
| 696 | goto fail_pipe; |
| 697 | } |
| 698 | cmd->in = fdin[1]; |
| 699 | } |
| 700 | |
| 701 | need_out = !cmd->no_stdout |
| 702 | && !cmd->stdout_to_stderr |
| 703 | && cmd->out < 0; |
| 704 | if (need_out) { |
| 705 | if (pipe(fdout) < 0) { |
| 706 | failed_errno = errno; |
| 707 | if (need_in) |
| 708 | close_pair(fdin); |
| 709 | else if (cmd->in) |
| 710 | close(cmd->in); |
| 711 | str = "standard output"; |
| 712 | goto fail_pipe; |
| 713 | } |
| 714 | cmd->out = fdout[0]; |
| 715 | } |
| 716 | |
| 717 | need_err = !cmd->no_stderr && cmd->err < 0; |
| 718 | if (need_err) { |
| 719 | if (pipe(fderr) < 0) { |
| 720 | failed_errno = errno; |
| 721 | if (need_in) |
| 722 | close_pair(fdin); |
| 723 | else if (cmd->in) |
| 724 | close(cmd->in); |
| 725 | if (need_out) |
| 726 | close_pair(fdout); |
| 727 | else if (cmd->out) |
| 728 | close(cmd->out); |
| 729 | str = "standard error"; |
| 730 | fail_pipe: |
| 731 | error("cannot create %s pipe for %s: %s", |
| 732 | str, cmd->args.v[0], strerror(failed_errno)); |
| 733 | child_process_clear(cmd); |
| 734 | errno = failed_errno; |