Pregunta

I'm doing something like this

def exitHandler(self, *args):
    self.stopThreads()
    sys.exit(2)

and I register that function in my self.run (working with a daemonized programm)

   signal.signal(signal.SIGTERM, self.exitHandler)

self.stopThreads() sometimes takes a while to finish. Im stopping subprocesses called started by those threads. When the signal handler gets called multiple times I get error messages like this:

Exception SystemExit: 2 in <bound method Popen.__del__ of <subprocess.Popen object at 0x929d10c>> ignored

Everything is fine, even with the ignored exception all my processes an threads finish as they should. I'm curious what I'm doing wrong and how to get rid of the ignored exception error.

¿Fue útil?

Solución

The problem appears to be that the work of either stopThreads() or sys.exit() is not reentrant, and the second SIGTERM causes one or both of those to be called in the middle of itself.

Now, you can't prevent the SIGTERM from being delivered multiple times, but you can rework your logic to accommodate it. The usual (and usually correct) advice is to refactor your signal handler to simply set a flag, and check for that flag in your main loop:

def termHandler(self, *args):
    global flag_exit
    global exit_code

    flag_exit = True
    exit_code = 2


... in the main loop ...

    while not flag_exit:
        do_work()

    self.stopThreads()
    sys.exit(exit_code)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top