Commit 576cd4ab authored by Léo-Paul Géneau's avatar Léo-Paul Géneau 👾

utils.py: Add exit class do handle signals

exit class can be used to handle signals and do proper cleaning before killing
a process
parent a90f0c6e
import array import array, signal, threading, os, sys
def checksum(pkt: bytes) -> bytes: def checksum(pkt: bytes) -> bytes:
...@@ -11,6 +11,45 @@ def checksum(pkt: bytes) -> bytes: ...@@ -11,6 +11,45 @@ def checksum(pkt: bytes) -> bytes:
return (((s >> 8) & 0xff) | s << 8) & 0xffff return (((s >> 8) & 0xff) | s << 8) & 0xffff
class exit(object):
status = None
def __init__(self):
l = threading.Lock()
self.acquire = l.acquire
r = l.release
def release():
try:
if self.status is not None:
self.release = r
sys.exit(self.status)
finally:
r()
self.release = release
def __enter__(self):
self.acquire()
def __exit__(self, t, v, tb):
self.release()
def kill_main(self, status):
self.status = status
os.kill(os.getpid(), signal.SIGTERM)
def signal(self, status, *sigs):
def handler(*args):
if self.status is None:
self.status = status
if self.acquire(0):
self.release()
for sig in sigs:
signal.signal(sig, handler)
exit = exit()
# obtain TYPE_CHECKING (for type hinting) # obtain TYPE_CHECKING (for type hinting)
try: try:
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment