def _autoclose_files(shielded=None, fallback_limit=1024):
''' Automatically close any open file descriptors.
shielded is iterable of file descriptors.
'''
# Process shielded.
shielded = default_to(shielded, [])
# Figure out the maximum number of files to try to close.
# This returns a tuple of softlimit, hardlimit; the hardlimit is always
# greater.
softlimit, hardlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
# If the hard limit is infinity, we can't iterate to it.
if hardlimit == resource.RLIM_INFINITY:
# Check the soft limit. If it's also infinity, fallback to guess.
if softlimit == resource.RLIM_INFINITY:
fdlimit = fallback_limit
# The soft limit is finite, so fallback to that.
else:
fdlimit = softlimit
# The hard limit is not infinity, so prefer it.
else:
fdlimit = hardlimit
# Skip fd 0, 1, 2, which are used by stdin, stdout, and stderr
# (respectively)
ranges_to_close = _make_range_tuples(
start = 3,
stop = fdlimit,
exclude = shielded
)
for start, stop in ranges_to_close:
# How nice of os to include this for us!
os.closerange(start, stop)
评论列表
文章目录