From 45aebdaca9ca7efeaa544c268e1a54cdc424f661 Mon Sep 17 00:00:00 2001 From: Douglas Raillard Date: Thu, 6 Apr 2023 21:39:53 +0100 Subject: [PATCH] connection: Ensure we don't leak too many BackgroundCommand Make BackgroundCommand.__init__() poll all current BackgroundCommands on the associated connection so they deregister themselves if they are completed. This ensures that a BackgroundCommand-heavy application that also does not close them properly will not accumulate useless instances forever and leak associated resources like Popen objects. --- devlib/connection.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/devlib/connection.py b/devlib/connection.py index f098a54..8c41055 100644 --- a/devlib/connection.py +++ b/devlib/connection.py @@ -123,6 +123,19 @@ class BackgroundCommand(ABC): def __init__(self, conn): self.conn = conn + + # Poll currently opened background commands on that connection to make + # them deregister themselves if they are completed. This avoids + # accumulating terminated commands and therefore leaking associated + # resources if the user is not careful and does not use the context + # manager API. + for bg_cmd in set(conn._current_bg_cmds): + try: + bg_cmd.poll() + # We don't want anything to fail here because of another command + except Exception: + pass + conn._current_bg_cmds.add(self) def _deregister(self):