[libc-commits] [libc] [libc] Implement close_range in unistd (PR #236913)
Pavel Labath via libc-commits
libc-commits at lists.llvm.org
Fri Oct 30 07:57:57 PDT 2026
================
@@ -0,0 +1,77 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Unittests for close_range.
+///
+//===----------------------------------------------------------------------===//
+
+#include "hdr/errno_macros.h"
+#include "hdr/fcntl_macros.h"
+#include "hdr/unistd_macros.h"
+#include "src/fcntl/fcntl.h"
+#include "src/unistd/close.h"
+#include "src/unistd/close_range.h"
+#include "src/unistd/pipe.h"
+#include "test/UnitTest/ErrnoCheckingTest.h"
+#include "test/UnitTest/ErrnoSetterMatcher.h"
+#include "test/UnitTest/Test.h"
+
+using namespace LIBC_NAMESPACE::testing::ErrnoSetterMatcher;
+using LlvmLibcCloseRangeTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;
+
+TEST_F(LlvmLibcCloseRangeTest, InvalidArgs) {
+ // first > last should fail with EINVAL.
+ ASSERT_THAT(LIBC_NAMESPACE::close_range(10, 5, 0), Fails(EINVAL));
+
+ // Unsupported or invalid flags should fail with EINVAL.
+ ASSERT_THAT(LIBC_NAMESPACE::close_range(10, 10, ~0U), Fails(EINVAL));
+}
+
+TEST_F(LlvmLibcCloseRangeTest, ClosePipes) {
+ int fds[2];
+ ASSERT_THAT(LIBC_NAMESPACE::pipe(fds), Succeeds(0));
+
+ int min_fd = fds[0] < fds[1] ? fds[0] : fds[1];
+ int max_fd = fds[0] > fds[1] ? fds[0] : fds[1];
----------------
labath wrote:
I'm slightly worried about this closing an unrelated FD if the returned FDs don't end up next to each other. I'd suggest something like the following loop (add error checking):
```
while (fds[0] + 1 != fds[1]) {
int new_fd = fcntl(fds[0], F_DUPFD, fds[1]);
close(fds[0]);
fds[0] = fds[1];
fds[1] = new_fd;
}
```
you can make a create_adjecant_fds() helper function for that.
https://github.com/llvm/llvm-project/pull/236913
More information about the libc-commits
mailing list