This decorator can be used to call a function holding with protection
from a given signal. The function should accept a dict of
utils.SignalHandler, indexed by signal number, and make use of it.

Signed-off-by: Guido Trotter <ultrot...@google.com>
---
 lib/utils.py |   28 ++++++++++++++++++++++++++++
 1 files changed, 28 insertions(+), 0 deletions(-)

diff --git a/lib/utils.py b/lib/utils.py
index 48f3e5d..5aac7d6 100644
--- a/lib/utils.py
+++ b/lib/utils.py
@@ -2053,6 +2053,34 @@ class FileLock(object):
                 "Failed to unlock %s" % self.filename)
 
 
+def SignalHandled(signums):
+  """Signal Handled decoration.
+
+  Calls the function installing a signal handler, and passing the SignalHandler
+  object to the function in a signal_handlers dict, indexed by signum.
+
+  @type signums: list
+  @param signums: signals to intercept
+
+  """
+  def wrap(fn):
+    def sig_function(*args, **kwargs):
+      if 'signal_handlers' in kwargs and not kwargs['signal_handlers'] is None:
+        signal_handlers = kwargs['signal_handlers']
+      else:
+        signal_handlers = {}
+        kwargs['signal_handlers'] = signal_handlers
+      sighandler = SignalHandler(signums)
+      try:
+        for sig in signums:
+          signal_handlers[sig] = sighandler
+        return fn(*args, **kwargs)
+      finally:
+        sighandler.Reset()
+    return sig_function
+  return wrap
+
+
 class SignalHandler(object):
   """Generic signal handler class.
 
-- 
1.5.6.5

Reply via email to