Skip to content

Commit f498720

Browse files
committed
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.
1 parent 1196655 commit f498720

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/basic/fd-util.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,21 @@ int close_all_fds(const int except[], size_t n_except) {
268268
return -errno;
269269

270270
have_close_range = false;
271+
272+
} else if (n_except == 1) {
273+
274+
/* Close all but exactly one, then we don't need no sorting. This is a pretty common
275+
* case, hence let's handle it specially. */
276+
277+
if ((except[0] <= 3 || close_range(3, except[0]-1, 0) >= 0) &&
278+
(except[0] >= INT_MAX || close_range(MAX(3, except[0]+1), -1, 0) >= 0))
279+
return 0;
280+
281+
if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
282+
return -errno;
283+
284+
have_close_range = false;
285+
271286
} else {
272287
_cleanup_free_ int *sorted_malloc = NULL;
273288
size_t n_sorted;

0 commit comments

Comments
 (0)