Skip to content

Commit 29a6461

Browse files
committed
run-command: add close_fd_above_stderr option
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>
1 parent 03cf12d commit 29a6461

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

run-command.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -832,6 +832,17 @@ int start_command(struct child_process *cmd)
832832
child_close(cmd->out);
833833
}
834834

835+
if (cmd->close_fd_above_stderr) {
836+
long max_fd = sysconf(_SC_OPEN_MAX);
837+
int fd;
838+
if (max_fd < 0 || max_fd > 4096)
839+
max_fd = 4096;
840+
for (fd = 3; fd < max_fd; fd++) {
841+
if (fd != child_notifier)
842+
close(fd);
843+
}
844+
}
845+
835846
if (cmd->dir && chdir(cmd->dir))
836847
child_die(CHILD_ERR_CHDIR);
837848

run-command.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,15 @@ struct child_process {
141141
unsigned stdout_to_stderr:1;
142142
unsigned clean_on_exit:1;
143143
unsigned wait_after_clean:1;
144+
145+
/**
146+
* Close file descriptors 3 and above in the child after forking
147+
* but before exec. This prevents the long-running child from
148+
* inheriting pipe endpoints or other descriptors from the parent
149+
* environment (e.g., the test harness).
150+
*/
151+
unsigned close_fd_above_stderr:1;
152+
144153
void (*clean_on_exit_handler)(struct child_process *process);
145154
};
146155

0 commit comments

Comments
 (0)