bpo-40422: create a common _Py_closerange API (GH-19754)

Such an API can be used both for os.closerange and subprocess. For the latter, this yields potential improvement for platforms that have fdwalk but wouldn't have used it there. This will prove even more beneficial later for platforms that have close_range(2), as the new API will prefer that over all else if it's available.

The new API is structured to look more like close_range(2), closing from [start, end] rather than the [low, high) of os.closerange().

Automerge-Triggered-By: @gpshead
This commit is contained in:
Kyle Evans 2020-10-11 13:54:11 -05:00 committed by GitHub
parent d5752aa5c9
commit c230fde847
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 51 additions and 37 deletions

View file

@ -250,7 +250,6 @@ _close_fds_by_brute_force(long start_fd, PyObject *py_fds_to_keep)
long end_fd = safe_get_max_fd();
Py_ssize_t num_fds_to_keep = PyTuple_GET_SIZE(py_fds_to_keep);
Py_ssize_t keep_seq_idx;
int fd_num;
/* As py_fds_to_keep is sorted we can loop through the list closing
* fds in between any in the keep list falling within our range. */
for (keep_seq_idx = 0; keep_seq_idx < num_fds_to_keep; ++keep_seq_idx) {
@ -258,21 +257,11 @@ _close_fds_by_brute_force(long start_fd, PyObject *py_fds_to_keep)
int keep_fd = PyLong_AsLong(py_keep_fd);
if (keep_fd < start_fd)
continue;
for (fd_num = start_fd; fd_num < keep_fd; ++fd_num) {
close(fd_num);
}
_Py_closerange(start_fd, keep_fd - 1);
start_fd = keep_fd + 1;
}
if (start_fd <= end_fd) {
#if defined(__FreeBSD__)
/* Any errors encountered while closing file descriptors are ignored */
closefrom(start_fd);
#else
for (fd_num = start_fd; fd_num < end_fd; ++fd_num) {
/* Ignore errors */
(void)close(fd_num);
}
#endif
_Py_closerange(start_fd, end_fd);
}
}