Function close_fds::close_open_fds[][src]

pub unsafe fn close_open_fds(minfd: c_int, keep_fds: &[c_int])

Close all open file descriptors starting at minfd, except for the file descriptors in keep_fds.

Safety

This function is NOT safe to use if other threads are interacting with files, networking, or anything else that could possibly involve file descriptors in any way, shape, or form. (Note: On some systems, file descriptor use may be more common than you think! For example, on Linux with musl libc, std::fs::canonicalize() will open a file descriptor to the given path.)

In addition, some objects, such as std::fs::File, may open file descriptors and then assume that they will remain open. This function, by closing those file descriptors, violates those assumptions.

This function is safe to use if it can be verified that these are not concerns. For example, it should be safe at startup or just before an exec(). At all other times, exercise extreme caution when using this function, as it may lead to race conditions and/or security issues.

(Note: The above warnings, by definition, make it unsafe to call this function concurrently from multiple threads. As a result, this function may perform other non-thread-safe operations.)

Efficiency

Efficiency of using keep_fds

If you’re going to be passing more than a few file descriptors in keep_fds, or if the file descriptors that you pass are high-numbered (i.e. 50 or 100), sort the slice first. This will give you significant performance improvements (especially on Linux 5.9+).

close_fds can’t just copy the slice and sort it for you because it’s a #![no_std] crate, so it can’t allocate memory.