You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Today, for everything that isn't the BSDs, we grab the
maximum number of open fds the process supports and then
loop through from 3 -> max, calling close(2) on everything.
Even for a low open fd count of 65k this will typically result
in 99+% of these close's being EBADF. At a 65k nofile RLIMIT
the sluggishness is not really felt, but on systems that may
have this in the millions it is extremely stark. `swift run`
on a hello world program can take minutes before the program
is actually ran.
There's a couple ways to work around this:
1. For Linux, on kernels 5.9 and up we have a handy friend named
close_range, which is similar to closefrom on the BSDs which we
already use.
2. If close_range doesn't exist we can read /proc/self/fd and
close everything manually above 3. It seems from some trial runs
there's really not all too many fds we hold open, so this is
around the same runtime as close_range. A similar avenue exists on
macOS in /dev/fd that we can use as well.
This change employs both of them for Linux, and only /dev/fd for macOS.
For Linux, we will try close_range first and if we get -1 (either for
ENOSYS as the syscall doesn't exist, or for any other error) we'll
fallback to the /proc method.
Below is the delta between two runs of `swift run` on a simple hello world
program. The shell I'm running these in has a nofile rlimit of 1 billion.
At 100 million it falls to about 20 seconds on my machine, and gets progressively
smaller until the two approaches aren't really any different at all.
With the patch:
```
Build of product 'closerange' complete! (0.17s)
Hello, world!
real 0m0.865s
user 0m0.702s
sys 0m0.110s
```
Without:
```
Build of product 'closerange' complete! (0.15s)
Hello, world!
real 2m43.203s
user 0m47.357s
sys 1m55.344s
```
Signed-off-by: Danny Canter <[email protected]>
0 commit comments