From: Paul Tarjan via GitGitGadget Date: Thu, 05 Mar 2026 01:16:14 GMT Subject: [PATCH v10 08/12] run-command: add pre-exec callback for child processes Message-ID: <39dcfbb7c8f870d8c520772563f1a3b0380929e0.1772673378.git.gitgitgadget@gmail.com> In-Reply-To: From: Paul Tarjan Add a pre_exec_cb function pointer to struct child_process that is invoked in the child between fork and exec. This gives callers a place to perform setup that must happen in the child's context, such as closing inherited file descriptors. Provide close_fd_above_stderr() as a ready-made callback that closes file descriptors 3 and above (skipping the child-notifier pipe), capped at sysconf(_SC_OPEN_MAX) or 4096, whichever is smaller. Signed-off-by: Paul Tarjan --- run-command.c | 18 ++++++++++++++++++ run-command.h | 16 ++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/run-command.c b/run-command.c index e3e02475cc..cfbfe68b33 100644 --- a/run-command.c +++ b/run-command.c @@ -546,8 +546,23 @@ static void atfork_parent(struct atfork_state *as) "restoring signal mask"); #endif } + #endif /* GIT_WINDOWS_NATIVE */ +void close_fd_above_stderr(void) +{ +#ifndef GIT_WINDOWS_NATIVE + 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); + } +#endif +} + static inline void set_cloexec(int fd) { int flags = fcntl(fd, F_GETFD); @@ -832,6 +847,9 @@ fail_pipe: child_close(cmd->out); } + if (cmd->pre_exec_cb) + cmd->pre_exec_cb(); + if (cmd->dir && chdir(cmd->dir)) child_die(CHILD_ERR_CHDIR); diff --git a/run-command.h b/run-command.h index 0df25e445f..375d2c731d 100644 --- a/run-command.h +++ b/run-command.h @@ -141,6 +141,14 @@ struct child_process { unsigned stdout_to_stderr:1; unsigned clean_on_exit:1; unsigned wait_after_clean:1; + + /** + * If set, the callback is invoked in the child between fork and + * exec. It can be used, for example, to close inherited file + * descriptors that the child should not keep open. + */ + void (*pre_exec_cb)(void); + void (*clean_on_exit_handler)(struct child_process *process); }; @@ -149,6 +157,14 @@ struct child_process { .env = STRVEC_INIT, \ } +/** + * Close file descriptors 3 and above. Suitable for use as a + * pre_exec_cb to prevent the child from inheriting pipe endpoints + * or other descriptors from the parent environment. On Windows + * this is a no-op since there is no fork/exec. + */ +void close_fd_above_stderr(void); + /** * The functions: start_command, finish_command, run_command do the following: * -- gitgitgadget