Close every open descriptor except those in *keep*. Only the descriptors listed by the fd directory are touched, so the cost does not grow with ``RLIMIT_NOFILE`` (issue #9886). billiard's implementation is still used as the fallback where no fd directory exists.
(keep=None)
| 348 | |
| 349 | |
| 350 | def close_open_fds(keep=None): |
| 351 | """Close every open descriptor except those in *keep*. |
| 352 | |
| 353 | Only the descriptors listed by the fd directory are touched, so the cost |
| 354 | does not grow with ``RLIMIT_NOFILE`` (issue #9886). billiard's |
| 355 | implementation is still used as the fallback where no fd directory exists. |
| 356 | """ |
| 357 | fds = _open_fds() |
| 358 | if fds is None: |
| 359 | # billiard walks range(get_fdmax()) in Python, which is what stalls |
| 360 | # in containers; only reachable without an fd directory. |
| 361 | _billiard_close_open_fds(keep) |
| 362 | return |
| 363 | keep = {fd for fd in map(maybe_fileno, keep or []) if fd is not None} |
| 364 | for fd in fds: |
| 365 | if fd in keep: |
| 366 | continue |
| 367 | try: |
| 368 | os.close(fd) |
| 369 | except OSError as exc: |
| 370 | if exc.errno != errno.EBADF: |
| 371 | raise |
| 372 | |
| 373 | |
| 374 | class DaemonContext: |