2aacef
From 60fa029fe83af62f27bf833dc86c0aeeb76b412b Mon Sep 17 00:00:00 2001
2aacef
From: Lennart Poettering <lennart@poettering.net>
2aacef
Date: Fri, 4 Nov 2022 18:19:29 +0100
2aacef
Subject: [PATCH] fd-util: make fd_in_set() (and thus close_all_fds()) handle
2aacef
 invalidated fds in the array
2aacef
2aacef
let's handle gracefully if fds in the specified array are already
2aacef
invalidated (i.e. negative). This is handy when putting together arrays
2aacef
on the fly.
2aacef
2aacef
(cherry picked from commit d11c14a9817f6561a30d96d8faea126a4c811af8)
2aacef
2aacef
Related: #2138081
2aacef
---
2aacef
 src/basic/fd-util.c | 10 +++++++++-
2aacef
 1 file changed, 9 insertions(+), 1 deletion(-)
2aacef
2aacef
diff --git a/src/basic/fd-util.c b/src/basic/fd-util.c
2aacef
index cee20a9a81..6ed04449bf 100644
2aacef
--- a/src/basic/fd-util.c
2aacef
+++ b/src/basic/fd-util.c
2aacef
@@ -177,9 +177,13 @@ int fd_cloexec(int fd, bool cloexec) {
2aacef
 _pure_ static bool fd_in_set(int fd, const int fdset[], size_t n_fdset) {
2aacef
         assert(n_fdset == 0 || fdset);
2aacef
 
2aacef
-        for (size_t i = 0; i < n_fdset; i++)
2aacef
+        for (size_t i = 0; i < n_fdset; i++) {
2aacef
+                if (fdset[i] < 0)
2aacef
+                        continue;
2aacef
+
2aacef
                 if (fdset[i] == fd)
2aacef
                         return true;
2aacef
+        }
2aacef
 
2aacef
         return false;
2aacef
 }
2aacef
@@ -252,6 +256,10 @@ static int close_all_fds_special_case(const int except[], size_t n_except) {
2aacef
         if (!have_close_range)
2aacef
                 return 0;
2aacef
 
2aacef
+        if (n_except == 1 && except[0] < 0) /* Minor optimization: if we only got one fd, and it's invalid,
2aacef
+                                             * we got none */
2aacef
+                n_except = 0;
2aacef
+
2aacef
         switch (n_except) {
2aacef
 
2aacef
         case 0: