[Python-Dev] forceful exit

tomer filiba tomerfiliba at gmail.com
Sun Jun 22 21:28:13 CEST 2008


hi

i'm having trouble when forking child processes to serve sockets. the
skeleton is something like the following:

def work():
    try:
        while True:
            s = listener.accept()[0]
            log("hello %s", s)
            if os.fork() == 0:
                try:
                    serve_client(sock)
                finally:
                    sys.exit()   #### <<<< (1)
            else:
                log("forked child")
                sock.close()
    except KeyboardInterrupt:
        log("got ctrl+c")
    finally:
        log("server terminated")
        listener.close()

the problem is that sys.exit() raises an exception, which propagates
all the way up and is handled by the finallies... the real code does
more than just printing logs, so i can't allow that.

i'm forced to resort to os._exit, which does the trick but doesn't
perform cleanup, which made me realize there's no clean way in python
to *force* exit.

i think there ought to be something like sys.forcedexit(), which
collects all objects nicely and then exits immediately without letting
anything propagate up. this will also solve another problem i came
across, with threads. turns out only the main thread can kill the
process -- if another thread issues sys.exit, it only kills itself.
there's no clean way for a thread to terminate the process... i think
there must be.

i can contribute a patch in a matter of days... i think it's pretty
straight forward (calling Py_Finalize and then exit). aye or nay?


-tomer


More information about the Python-Dev mailing list