def wait_fds(fd_events, inmask=1, outmask=2, timeout=None):
    current = compat.getcurrent()
    activated = {}
    poll_regs = {}
    callback_refs = {}
    def activate(fd, event):
        if not activated and timeout != 0:
            scheduler.schedule(current)
            if timeout:
                scheduler._remove_timer(waketime, current)
        activated.setdefault(fd, 0)
        activated[fd] |= event
    for fd, events in fd_events:
        readable = None
        writable = None
        if events & inmask:
            readable = functools.partial(activate, fd, inmask)
        if events & outmask:
            writable = functools.partial(activate, fd, outmask)
        callback_refs[fd] = (readable, writable)
        poll_regs[fd] = scheduler._register_fd(fd, readable, writable)
    if timeout:
        waketime = time.time() + timeout
        scheduler.pause_until(waketime)
    elif timeout == 0:
        scheduler.pause()
    else:
        scheduler.state.mainloop.switch()
    for fd, reg in poll_regs.iteritems():
        readable, writable = callback_refs[fd]
        scheduler._unregister_fd(fd, readable, writable, reg)
    if scheduler.state.interrupted:
        raise IOError(errno.EINTR, "interrupted system call")
    return activated.items()