From c60499e689fd8ea1ee4db269fcd3a7f2ab7fbb08 Mon Sep 17 00:00:00 2001 From: Ingmar Steen Date: Mon, 11 Feb 2019 14:55:24 +0100 Subject: [PATCH] Fix hang on KeyboardInterrupt when running with asyncio. (#95) * Fix hang on KeyboardInterrupt when running with asyncio. The bare except in the _service_task function also catches and ignores asyncio.CancelledError exceptions. This means the function will never gracefully exit when cancelling the task. The solution I propose here adds an additional except handler specifically for asyncio.CancelledError which will then stop the service task. This allows f.e. aiohttp to cancel all pending tasks and allows the process to terminate even when there are connected clients. * Also exit service task on KeyboardInterrupt. --- engineio/asyncio_server.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/engineio/asyncio_server.py b/engineio/asyncio_server.py index 37c78b5a..54d0ed20 100644 --- a/engineio/asyncio_server.py +++ b/engineio/asyncio_server.py @@ -415,6 +415,9 @@ async def _service_task(self): # pragma: no cover if not socket.closing and not socket.closed: await socket.check_ping_timeout() await self.sleep(sleep_interval) + except (KeyboardInterrupt, asyncio.CancelledError): + self.logger.debug('service task cancelled') + break except: # an unexpected exception has occurred, log it and continue self.logger.exception('service task exception')