ac3a84
From b9223cd76c73fa5cf3ed19a2238980047bf13826 Mon Sep 17 00:00:00 2001
ac3a84
From: Lennart Poettering <lennart@poettering.net>
ac3a84
Date: Fri, 4 Nov 2022 18:20:19 +0100
ac3a84
Subject: [PATCH] fd-util: add new fd_cloexec_many() helper
ac3a84
ac3a84
(cherry picked from commit ed18c22c989495aab36512f03449222cfcf79aa7)
ac3a84
ac3a84
Related: #2138081
ac3a84
---
ac3a84
 src/basic/fd-util.c | 19 +++++++++++++++++++
ac3a84
 src/basic/fd-util.h |  1 +
ac3a84
 2 files changed, 20 insertions(+)
ac3a84
ac3a84
diff --git a/src/basic/fd-util.c b/src/basic/fd-util.c
ac3a84
index 6ed04449bf..66bb7569bb 100644
ac3a84
--- a/src/basic/fd-util.c
ac3a84
+++ b/src/basic/fd-util.c
ac3a84
@@ -174,6 +174,25 @@ int fd_cloexec(int fd, bool cloexec) {
ac3a84
         return RET_NERRNO(fcntl(fd, F_SETFD, nflags));
ac3a84
 }
ac3a84
 
ac3a84
+int fd_cloexec_many(const int fds[], size_t n_fds, bool cloexec) {
ac3a84
+        int ret = 0, r;
ac3a84
+
ac3a84
+        assert(n_fds == 0 || fds);
ac3a84
+
ac3a84
+        for (size_t i = 0; i < n_fds; i++) {
ac3a84
+                if (fds[i] < 0) /* Skip gracefully over already invalidated fds */
ac3a84
+                        continue;
ac3a84
+
ac3a84
+                r = fd_cloexec(fds[i], cloexec);
ac3a84
+                if (r < 0 && ret >= 0) /* Continue going, but return first error */
ac3a84
+                        ret = r;
ac3a84
+                else
ac3a84
+                        ret = 1; /* report if we did anything */
ac3a84
+        }
ac3a84
+
ac3a84
+        return ret;
ac3a84
+}
ac3a84
+
ac3a84
 _pure_ static bool fd_in_set(int fd, const int fdset[], size_t n_fdset) {
ac3a84
         assert(n_fdset == 0 || fdset);
ac3a84
 
ac3a84
diff --git a/src/basic/fd-util.h b/src/basic/fd-util.h
ac3a84
index d9896e27e8..29c7d86f27 100644
ac3a84
--- a/src/basic/fd-util.h
ac3a84
+++ b/src/basic/fd-util.h
ac3a84
@@ -56,6 +56,7 @@ DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(DIR*, closedir, NULL);
ac3a84
 
ac3a84
 int fd_nonblock(int fd, bool nonblock);
ac3a84
 int fd_cloexec(int fd, bool cloexec);
ac3a84
+int fd_cloexec_many(const int fds[], size_t n_fds, bool cloexec);
ac3a84
 
ac3a84
 int get_max_fd(void);
ac3a84