#!/usr/local/bin/python
#
# adzapper
# Copyright 1999 - 2001 Adam Feuer
# Adam Feuer <adamf@pobox.com>
#
# This file is part of adzapper.
#
# adzapper is free software; you can redistribute it and/or modify
# it under the terms of the Python License, as published by the
# Python Software Foundation.
#
# adzapper is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# Python License for more details.
#
# You should have received a copy of the Python License along
# with adzapper; see the file COPYING.
#
#
# this provides a method used to override the asyncore.poll method--
# to allow us to catch SIGHUP signals during an I/O event
#
RCS_ID =  '$Id: asyncore_fixes.py,v 1.4 2001/09/02 04:47:16 adamf Exp $'

import asyncore
import select
import exceptions

DEBUG = 0

class ExitNow (exceptions.Exception):
        pass


def a_poll (timeout=0.0):
	if asyncore.socket_map:
		r = []; w = []; e = []
		for s in asyncore.socket_map.keys():
			if s.readable():
				r.append (s)
			if s.writable():
				w.append (s)

                # SIGHUP will interrupt the select() system call--
                # make sure we restart it if that happens.
                selectErrNum = 4
                while (selectErrNum == 4):
                                selectErrNum = 0
                                try:
                                                (r,w,e) = select.select (r,w,e, timeout)
                                except select.error, val:
                                                selectErrNum = val[0]
        

		for x in r:
			try:
				x.handle_read_event()
			except:
				x.handle_error()
		for x in w:
			try:
				x.handle_write_event()
			except:
				x.handle_error()



def b_poll (timeout=0.0, map=None):
	global DEBUG
	if map is None:
		map = socket_map
	if map:
		r = []; w = []; e = []
		for fd, obj in map.items():
			if obj.readable():
				r.append (fd)
			if obj.writable():
				w.append (fd)

                # SIGHUP will interrupt the select() system call--
                # make sure we restart it if that happens.
                selectErrNum = 4
                while (selectErrNum == 4):
                                selectErrNum = 0
                                try:
                                                (r,w,e) = select.select (r,w,e, timeout)
                                except select.error, val:
                                                selectErrNum = val[0]
        

		if DEBUG:
			print r,w,e

		for fd in r:
			try:
				obj = map[fd]
				try:
					obj.handle_read_event()
				except ExitNow:
					raise ExitNow
				except:
					obj.handle_error()
			except KeyError:
				pass

		for fd in w:
			try:
				obj = map[fd]
				try:
					obj.handle_write_event()
				except ExitNow:
					raise ExitNow
				except:
					obj.handle_error()
			except KeyError:
				pass
