Using a signal to terminate a programm running with an asyncore loop

david at david at
Tue Feb 19 22:02:18 CET 2008

On Feb 8, 4:03 pm, Larry Bates < at> wrote:
> When signal is caught handle_shutdown_signal is called.  At that point
> SHUTDOWN_PERFORMED will ALWAYS be False.  Normally all you do in this function
> is to set SHUTDOWN_PERFORMED to True and have a test somewhere in your main
> program loop that tests if SHUTDOWN_PERFORMED:...  I know that when you reach
> SHUTDOWN_PERFORMED will always be False so #do some stuff will get executed.
> Setting SHUTDOWN_PERFORMED = True doesn't do any good unless you catch this back
> in the main program.
> If I were you I would try to issue kill from console first to see if it works.
> Then try os.kill().
> Hope this helps some.
> -Larry

Sorry for the slow response.  I had other tasks come up last week that
took priority.  Got back to this today and tried it.  I simplified my
code so right now the signal handler looks like this:

def handle_shutdown_signal(signum, frame):
   print 'in shutdown handler, caught signal', signum

I'm still registering the handler the same way:

   signal.signal(signal.SIGTERM, handle_shutdown_signal)

I'm still not convinced the handler function is getting called.  I
tried killing the process from the command line (# kill -s SIGTERM
<pid>) and my print message doesn't get shown; and running ps ax shows
the program is still running.

I'm wondering if there is something else going on.  I've checked my
code and nothing else registers any signal handlers, but there are
places that use asyncore.dispatcher and asynchat to handle some
network communication; perhaps something in there re-registers the
signal handlers?

I tried writing a simple test program; running it from one shell and
killing it from another works fine:

#!/usr/bin/env python
import signal
def handler(signum, frame):
        print 'caught signal', signum
signal.signal(signal.SIGTERM, handler)
while True:
        a = 1
print 'out'

After I issue the fill command, I get the following output:

caught signal 15

Which is what I expected; since the handler calls exit() I didn't
expect to see the 'out' message ever get printed.

Any thoughts?

- David

More information about the Python-list mailing list