def closeall(**params):
    """
    Close all file descriptors.  This turns out to be harder than you'd
    think.  For example, here is a discussion:

    http://stackoverflow.com/questions/899038/getting-the-highest-allocated-file-descriptor

    The default algorithm here is to close until "closeall.beyond_last_fd"
    close failures are registered.  The default value can be overriden.
    In some cases where a daemon handles a large number of connections,
    this approach may not be sufficient, so the "maxfd" param below
    alters the approach.

    Supported params are:

        exclude - Exclude the file descriptors in the int list provided
        beyond  - Override the closeall.beyond_last_fd value.
        maxfd   - If True, the system NOFILE value is used and closes
              will be attempted through this range.  If an int,
              the value will be used as a maximum.

    The method is intended to be safe against weird input and will never
    raise an exception.

    The method returns the highest fd closed or None if none were closed.
    It can be useful to log the highest fd because it can indicate a file
    descriptor leak in a parent process.
"""
    exclude_list = params.get('exclude')
    beyond = params.get('beyond')
    maxfd = params.get('maxfd')

    if maxfd:
        beyond = None
    elif not beyond:
        beyond = closeall.beyond_last_fd

    excludes = {}
    if exclude_list is not None:
        try:
            for s in exclude_list:
                _pick_fd(s, excludes)
        except:                                 # pragma: no cover
            _pick_fd(exclude_list, excludes)

    #  Find the largest excluded fd
    exlist = list(excludes)
    if len(exlist) > 0:
        exlist.sort(reverse=True)
        last_exc_fd = exlist[0]
    else:                                       # pragma: no cover
        last_exc_fd = None

    #  Find the maximum available fd

    if maxfd is True:
        maxfd = sys_maxfd()

    highest = -1
    fd = 0
    while True:
        if maxfd is None:
            if fd > highest + beyond:
                break
        elif fd > maxfd:
            break
        if not excludes.get(fd):
            try:
                os.close(fd)
                highest = fd
            except:
                pass
        fd += 1
    if highest == -1:
        return None
    else:
        return highest