import fcntl


def log_filenos(log, cloexec=True):
    """
        Identify the filenos (unix file descriptors) of a logging object.
        This is most commonly used to avoid closing the log file descriptors
        after a fork so information can be logged before an exec().

        To prevent conficts and potential hangs, the default is to set the
        fcntl.FD_CLOEXEC close-on-exec flag for the file descriptors found.
        The can be inhibited with the 'cloexec' param.
    """
    filenos = []
    try:
        for handler in log.handlers:
            for name in dir(handler):
                attr = getattr(handler, name, None)
                if attr and hasattr(attr, 'fileno') and callable(attr.fileno):
                    filenos.append(attr.fileno())
        for fd in filenos:
            fl = fcntl.fcntl(fd, fcntl.F_GETFL)
            fcntl.fcntl(fd, fcntl.F_SETFL, fl | fcntl.FD_CLOEXEC)
    except:
        pass
    return filenos