]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
fd-util: special case invocation of close_all_fds() with single exception fd
authorLennart Poettering <lennart@poettering.net>
Tue, 12 Oct 2021 13:53:55 +0000 (15:53 +0200)
committerLennart Poettering <lennart@poettering.net>
Wed, 27 Oct 2021 15:56:36 +0000 (17:56 +0200)
Add special case optimization for a single exception fd. It's a
pretty common case in our codebase, and the optimization is simple
and means we don't need to copy/sort the exception array, so do it.

src/basic/fd-util.c

index 274bbb32cc04b32b3b0e62e80535da522bfa4c40..658b17fed726500611cb48ee69cac820d37bdb9e 100644 (file)
@@ -268,6 +268,21 @@ int close_all_fds(const int except[], size_t n_except) {
                                 return -errno;
 
                         have_close_range = false;
+
+                } else if (n_except == 1) {
+
+                        /* Close all but exactly one, then we don't need no sorting. This is a pretty common
+                         * case, hence let's handle it specially. */
+
+                        if ((except[0] <= 3 || close_range(3, except[0]-1, 0) >= 0) &&
+                            (except[0] >= INT_MAX || close_range(MAX(3, except[0]+1), -1, 0) >= 0))
+                                return 0;
+
+                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
+                                return -errno;
+
+                        have_close_range = false;
+
                 } else {
                         _cleanup_free_ int *sorted_malloc = NULL;
                         size_t n_sorted;