1 /* Return a range of open file descriptors.
2 Copyright (C) 2021-2023 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
21 #include <support/support.h>
22 #include <support/check.h>
23 #include <support/xunistd.h>
25 #include <sys/resource.h>
28 increase_nofile (void)
31 if (getrlimit (RLIMIT_NOFILE, &rl) == -1)
32 FAIL_EXIT1 ("getrlimit (RLIMIT_NOFILE): %m");
36 if (setrlimit (RLIMIT_NOFILE, &rl) == 1)
37 FAIL_EXIT1 ("setrlimit (RLIMIT_NOFILE): %m");
41 open_dev_null (int flags, mode_t mode)
43 int fd = open64 ("/dev/null", flags, mode);
47 if (fd < 0 && errno != EMFILE)
48 FAIL_EXIT1 ("open64 (\"/dev/null\", 0x%x, 0%o): %m", flags, mode);
52 return xopen ("/dev/null", flags, mode);
69 range_init (struct range_list *r)
73 r->ranges = xmalloc (r->total * sizeof (struct range));
77 range_add (struct range_list *r, int lowfd, size_t len)
79 if (r->used == r->total)
82 r->ranges = xrealloc (r->ranges, r->total * sizeof (struct range));
84 r->ranges[r->used].lowfd = lowfd;
85 r->ranges[r->used].len = len;
90 range_close (struct range_list *r)
92 for (size_t i = 0; i < r->used; i++)
94 int minfd = r->ranges[i].lowfd;
95 int maxfd = r->ranges[i].lowfd + r->ranges[i].len;
96 for (int fd = minfd; fd < maxfd; fd++)
103 support_open_dev_null_range (int num, int flags, mode_t mode)
105 /* We keep track of the ranges that hit an already opened descriptor, so
106 we close them after we get a working range. */
107 struct range_list rl;
110 int lowfd = open_dev_null (flags, mode);
117 int fd = open_dev_null (flags, mode);
120 range_add (&rl, lowfd, prevfd - lowfd + 1);