Re: [PATCH v8 08/12] run-command: add close_fd_above_stderr option
- From
Junio C Hamano <gitster@pobox.com>
- Date
- Mar 4, 2026, 20:51 UTC
- Message-ID
- <xmqq8qc771zf.fsf@gitster.g>
- In-Reply-To
- <29a6461915ce9d2abedb29e475d589bb8d24934a.1772648125.git.gitgitgadget@gmail.com>
"Paul Tarjan via GitGitGadget" <gitgitgadget@gmail.com> writes:
Show 38 quoted lines
> From: Paul Tarjan <github@paulisageek.com>
>
> Add a new option to struct child_process that closes file descriptors
> 3 and above in the child after forking but before exec. Without this,
> long-running child processes inherit pipe endpoints and other
> descriptors from the parent environment.
>
> The upper bound for the fd scan comes from sysconf(_SC_OPEN_MAX),
> capped at 4096 to avoid excessive iteration when the limit is set
> very high.
>
> Signed-off-by: Paul Tarjan <github@paulisageek.com>
> ---
> run-command.c | 11 +++++++++++
> run-command.h | 9 +++++++++
> 2 files changed, 20 insertions(+)
>
> diff --git a/run-command.c b/run-command.c
> index e3e02475cc..cbadcf5ff8 100644
> --- a/run-command.c
> +++ b/run-command.c
> @@ -832,6 +832,17 @@ fail_pipe:
> child_close(cmd->out);
> }
>
> + if (cmd->close_fd_above_stderr) {
> + long max_fd = sysconf(_SC_OPEN_MAX);
> + int fd;
> + if (max_fd < 0 || max_fd > 4096)
> + max_fd = 4096;
> + for (fd = 3; fd < max_fd; fd++) {
> + if (fd != child_notifier)
> + close(fd);
> + }
> + }
> +
> if (cmd->dir && chdir(cmd->dir))
> child_die(CHILD_ERR_CHDIR);The need for this particular "close file descriptors other than the standard ones" may be common enough that I do not mind to have it inside "run-command.c", but I wonder if a generic callback function to call here in the child between fork and exec that the caller can supply would be a good thing to have. Then, any caller who may want to set close_fd_above_stderr could instead prepare a callback that does the body of the above if statement themselves.
Show 19 quoted lines
> diff --git a/run-command.h b/run-command.h
> index 0df25e445f..a1aa1b1069 100644
> --- a/run-command.h
> +++ b/run-command.h
> @@ -141,6 +141,15 @@ struct child_process {
> unsigned stdout_to_stderr:1;
> unsigned clean_on_exit:1;
> unsigned wait_after_clean:1;
> +
> + /**
> + * Close file descriptors 3 and above in the child after forking
> + * but before exec. This prevents the long-running child from
> + * inheriting pipe endpoints or other descriptors from the parent
> + * environment (e.g., the test harness).
> + */
> + unsigned close_fd_above_stderr:1;
> +
> void (*clean_on_exit_handler)(struct child_process *process);
> };