Any way to restrict execution with regard to execution time??

William Annis annis at biostat.wisc.edu
Wed Jan 17 13:58:23 EST 2001


rturpin at my-deja.com writes:

> So here's the problem, that seems intractable in Python.

        Amazing.  I've been worrying about this problem quite a lot
recently, and here's a question on it.

> There are two pieces of code, C1 and C2. C1 wants to run
> C2, but does not trust it to consume only a reasonable
> amount of time (measured in any fashion). How can C1 run
> C2 guaranteeing that C2's execution is interrupted after
> some finite amount of time, if it hasn't finished by
> then? C2 is from an untrusted source, so the answer
> cannot be phrased in terms of how C2 is written. I'd be
> much obliged to anyone who can tell me how to do this!

        Have you tried using signals and a timeout?  I have little
script which is simply an IP filter: if it sees something in stream of
text that looks like an IP address, it tries to lookup the name
associated with that.  This operation can time out, making the program
pretty slow sometimes, so I added a 5 second limit on the lookup:

----------------------------------------
import socket
from signal import signal, alarm, SIGALRM

# Register our timeout signal handler.
class Timeout(Exception): pass

def throw_timeout(sig, frame):
    raise Timeout(sig)

signal(SIGALRM, throw_timeout)

# <some code snipped>

# Return the resolved address if it exists, otherwise, just give back
# the IP version.
def lookup(addr):
    # If this address has been cached, use it; otherwise lookup into cache.
    if not ips.has_key(addr):
        ips[addr] = addr       # default == the IP addr string

        try:
            # Don't wait too long for an answer.
            alarm(5)
            (ips[addr], more, ip) = socket.gethostbyaddr(addr)
            alarm(0)
        except socket.error:
            # Lookup failed.  Reset alarm.
            alarm(0)
        except Timeout:
            # Lookup took too long.  Move on.
            pass
            
    return ips[addr]
----------------------------------------

        Just substitute C2 for the gethostbuaddr() call.

        This works reasonably well for simple situations like the
lookup above.  However, in more complex programs you have a serious
state issue.  If the code you're calling is actually doing work and
changing variables when it times out, you may be left in a strange
state.  Recovering from that seems a bigger problem to me.

-- 
William Annis - System Administrator - Biomedical Computing Group
annis at biostat.wisc.edu                       PGP ID:1024/FBF64031
Mi parolas Esperanton - La Internacian Lingvon  www.esperanto.org



More information about the Python-list mailing list