Skip to content

Commit da089af

Browse files
authored
Merge pull request #3 from lutzfischer/cleanup
improve signal handlers
2 parents c87b023 + e16ec87 commit da089af

1 file changed

Lines changed: 36 additions & 10 deletions

File tree

dirlock/__init__.py

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,17 @@
2020
# keep a list of currently acquired locks
2121
# so these can be cleaned up on exit
2222
_allActiveLocks = set()
23-
# we don't want to call the original handler
24-
original_sigint_handler = signal.getsignal(signal.SIGINT)
25-
original_sigterm_handler = signal.getsignal(signal.SIGTERM)
23+
24+
# we don't want to miss the original handler
25+
try:
26+
original_sigint_handler = signal.getsignal(signal.SIGINT)
27+
except Exception:
28+
pass
29+
30+
try:
31+
original_sigterm_handler = signal.getsignal(signal.SIGTERM)
32+
except Exception:
33+
pass
2634

2735

2836
# function to clean up all active locks
@@ -32,7 +40,6 @@ def _clean_locks():
3240
locks_to_release = list(_allActiveLocks)
3341
for dl in locks_to_release:
3442
dl.release()
35-
_allActiveLocks.remove(dl)
3643

3744

3845
def handle_sigint_cleanup(signum, frame):
@@ -44,7 +51,13 @@ def handle_sigint_cleanup(signum, frame):
4451
global original_sigint_handler
4552
_clean_locks()
4653
if original_sigint_handler is not None:
47-
original_sigint_handler(signum, frame)
54+
# restore the original handler
55+
if callable(original_sigint_handler):
56+
original_sigint_handler(signum, frame)
57+
else:
58+
signal.signal(signal.SIGINT, original_sigint_handler)
59+
# and re-raise the signal
60+
os.kill(os.getpid(), signal.SIGINT)
4861

4962

5063
def handle_sigterm_cleanup(signum, frame):
@@ -56,16 +69,29 @@ def handle_sigterm_cleanup(signum, frame):
5669
global original_sigterm_handler
5770
_clean_locks()
5871
if original_sigterm_handler is not None:
59-
original_sigterm_handler(signum, frame)
72+
# restore the original handler
73+
if callable(original_sigterm_handler):
74+
original_sigterm_handler(signum, frame)
75+
else:
76+
signal.signal(signal.SIGTERM, original_sigterm_handler)
77+
# and re-raise the signal
78+
os.kill(os.getpid(), signal.SIGTERM)
6079

6180

6281
# normal exit clean up
6382
atexit.register(_clean_locks)
6483

65-
# ctrl+c cleanup
66-
signal.signal(signal.SIGINT, handle_sigint_cleanup)
67-
# sigterm cleanup
68-
signal.signal(signal.SIGTERM, handle_sigterm_cleanup)
84+
try:
85+
# ctrl+c cleanup
86+
signal.signal(signal.SIGINT, handle_sigint_cleanup)
87+
except Exception:
88+
pass
89+
90+
try:
91+
# sigterm cleanup
92+
signal.signal(signal.SIGTERM, handle_sigterm_cleanup)
93+
except Exception:
94+
pass
6995

7096

7197
class DirLock:

0 commit comments

Comments
 (0)