TERM Signal Capture in Gevent-Based Applications

I wrote a simple daemon in Python that is based on Gevent. The daemon needs to do some cleanup before it exists, so it needs to be able to process the TERM signal, transform its cleanup, and exit gracefully. In one streaming daemon that is not based on Gevent, I used the Python signal module to set the signal handler for the TERM signal. The signal handler throws a user-defined exception called TermSignal. The main daemon thread can simply catch the TermSignal exception, clear it, and exit.

This solution did not work as expected when I tried to implement it in a Gevent-based daemon. The demon has a major green that calls joinallon working greens. the call joinallends in a try / except block that catches KeyboardInterrupt, which allows the daemons to reformat its cleanup when it starts without demonization. However, when I executed the above solution and sent a TERM signal to the process, I could see in the console window that one of the working potions raised an exception TermSignalinstead of the main grill. This uncaught exception did not dictate the underlying greens, despite the face that I called joinallwith the option raise_errorset to True. As a result, one of the green workers crashed due to an exception, but the demon did not come out at all.

+4
source share
1 answer

After I did a few searches, I found a solution. As mentioned here , Gevent monkey patching does not fix the signal.signalPython built-in function . In order for my solution to work, the main greens must call gevent.signalinstead signal.signalto install the handler. In addition, it gevent.signalexpects handler functions that take no arguments, unlike signal.signal, which expects handler functions that take 2 arguments. Since I still don't care about these arguments, I changed my term handler as follows:

def _term_handler(*_):
    raise TermSignal()

, Gevent Python. , (signal.signal gevent.signal)

+7

All Articles