From: Lennart Poettering Date: Tue, 12 Oct 2021 13:53:55 +0000 (+0200) Subject: fd-util: special case invocation of close_all_fds() with single exception fd X-Git-Tag: v250-rc1~399^2~6 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=f498720a3464434e6df9bcfc54ccc8d8594ac2ff;p=thirdparty%2Fsystemd.git fd-util: special case invocation of close_all_fds() with single exception fd 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. --- diff --git a/src/basic/fd-util.c b/src/basic/fd-util.c index 274bbb32cc0..658b17fed72 100644 --- a/src/basic/fd-util.c +++ b/src/basic/fd-util.c @@ -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;