cronie/optimization_to_close_fds.p...

53 lines
1.5 KiB
Diff

From e3682c7135b9176b60d226c60ee4e78cf1ab711b Mon Sep 17 00:00:00 2001
From: bwelterl <bwelterl@redhat.com>
Date: Thu, 7 Sep 2023 10:05:36 +0200
Subject: [PATCH] Optimization to close fds from /proc/self/fd in case of high
nofile limit after fork
---
src/do_command.c | 23 ++++++++++++++++++++---
1 file changed, 20 insertions(+), 3 deletions(-)
diff --git a/src/do_command.c b/src/do_command.c
index 500f1b0..665e1f0 100644
--- a/src/do_command.c
+++ b/src/do_command.c
@@ -30,6 +30,7 @@
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
+#include <dirent.h>
#include "externs.h"
#include "funcs.h"
@@ -264,10 +265,26 @@ static int child_process(entry * e, char **jobenv) {
{
char *shell = env_get("SHELL", jobenv);
int fd, fdmax = TMIN(getdtablesize(), MAX_CLOSE_FD);
+ DIR *dir;
+ struct dirent *dent;
- /* close all unwanted open file descriptors */
- for(fd = STDERR + 1; fd < fdmax; fd++) {
- close(fd);
+ /*
+ * if /proc is mounted, we can optimize what fd can be closed,
+ * but if it isn't available, fall back to the previous behavior.
+ */
+ if ((dir = opendir("/proc/self/fd")) != NULL) {
+ while ((dent = readdir(dir)) != NULL) {
+ if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
+ continue;
+ fd = atoi(dent->d_name);
+ if (fd > STDERR_FILENO)
+ close(fd);
+ }
+ } else {
+ /* close all unwanted open file descriptors */
+ for (fd = STDERR + 1; fd < fdmax; fd++) {
+ close(fd);
+ }
}
#if DEBUGGING