From 438d329d0d3ea35ba0a69319c594c789cecc8680 Mon Sep 17 00:00:00 2001 From: Sviatoslav Sydorenko Date: Fri, 12 Feb 2021 15:32:18 +0100 Subject: [PATCH] Close hanging file handles with a CM --- magicbus/plugins/opsys.py | 12 ++++++++---- magicbus/test/test_opsys.py | 4 +++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/magicbus/plugins/opsys.py b/magicbus/plugins/opsys.py index d2fd5ad2..4be4ff3c 100644 --- a/magicbus/plugins/opsys.py +++ b/magicbus/plugins/opsys.py @@ -236,7 +236,8 @@ def ENTER(self): if self.finalized: self.bus.log('PID %r already written to %r.' % (pid, self.pidfile)) else: - open(self.pidfile, 'wb').write(ntob('%s' % pid, 'utf8')) + with open(self.pidfile, 'wb') as pid_file: + pid_file.write(ntob('%s' % pid, 'utf8')) self.bus.log('PID %r written to %r.' % (pid, self.pidfile)) self.finalized = True ENTER.priority = 70 @@ -255,9 +256,12 @@ def wait(self, timeout=None, poll_interval=0.1): """ starttime = time.time() while timeout is None or time.time() - starttime <= timeout: - if os.path.exists(self.pidfile): - return int(open(self.pidfile, 'rb').read()) - time.sleep(poll_interval) + if not os.path.exists(self.pidfile): + time.sleep(poll_interval) + continue + + with open(self.pidfile, 'rb') as pid_file: + return int(pid_file.read()) def join(self, timeout=None, poll_interval=0.1): """Return when the PID file does not exist, or the timeout expires.""" diff --git a/magicbus/test/test_opsys.py b/magicbus/test/test_opsys.py index c40b6740..f88fc70e 100644 --- a/magicbus/test/test_opsys.py +++ b/magicbus/test/test_opsys.py @@ -48,7 +48,9 @@ def test_daemonize(self): resp = service.do_GET('/pid') assert resp.status == 200 page_pid = int(resp.read()) - assert ntob(str(page_pid)) == open(pidfile.pidfile, 'rb').read() + with open(pidfile.pidfile, 'rb') as pid_file: + actual_pid = pid_file.read() + assert ntob(str(page_pid)) == actual_pid finally: # Shut down the spawned process service.do_GET('/exit')