close_fds

crates.io Docs GitHub Actions Cirrus CI codecov

A small Rust library that makes it easy to close all open file descriptors.

Usage

Add to your Cargo.toml:

[dependencies] close_fds = "0.2"

In your application:

``` use closefds::closeopen_fds;

fn main() { // ... unsafe { closeopenfds(3, &[]); } // ... } ```

IMPORTANT: Please read the documentation for close_open_fds() for an explanation of why it is unsafe.

The first argument to close_open_fds() is the lowest file descriptor that should be closed; all file descriptors less than this will be left open. The second argument is a slice containing a list of additional file descriptors that should be left open. (Note: close_open_fds() will be more efficient if this list is sorted, especially if it is more than a few elements long.)

close_open_fds() always succeeds. If one method of closing the file descriptors fails, it will fall back on another.

Some other helpful functions in this crate (more details in the documentation):

In addition, there are "thread-safe" versions of these three functions that behave more reliably in multithreaded programs (at the cost of increased performance on some platforms). See the documentation for more details.

Note that close_open_fds() should be preferred whenever possible, as it may be able to take advantage of platform-specific optimizations that these other functions cannot.

OS support

close_fds has two OS support tiers, similar to Rust's support tiers:

Tier 1: "Guaranteed to work" (tested in CI)

Tier 2: "Guaranteed to build" (built, but not tested, in CI)

Note: As stated in the license, close_fds comes with no warranty.

OS-specific notes

Here is a list of the methods that iter_open_fds(), iter_possible_fds(), close_open_fds(), and set_fds_cloexec() will try on various platforms to improve performance when listing the open file descriptors:

In certain circumstances, close_open_fds() may also call closefrom() on the BSDs and/or close_range() on Linux 5.9+/FreeBSD 12.2+, both of which are very efficient.

If none of the methods listed above are available, it will fall back on a simple loop through every possible file descriptor number -- from minfd to sysconf(_SC_OPEN_MAX). This is slow, but it will always work.

Note: The most common use case, close_open_fds(3, &[]), is very efficient on Linux (with /proc mounted, or on kernel 5.9+), macOS, all of the BSDs, and Solaris/Illumos.