1 # Copyright (c) 2010, 2011 Nicira Networks
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
22 def add_hook(hook, cancel, run_at_exit):
26 _hooks.append((hook, cancel, run_at_exit))
29 """Clears all of the fatal signal hooks without executing them. If any of
30 the hooks passed a 'cancel' function to add_hook(), then those functions
31 will be called, allowing them to free resources, etc.
33 Following a fork, one of the resulting processes can call this function to
34 allow it to terminate without calling the hooks registered before calling
35 this function. New hooks registered after calling this function will take
38 for hook, cancel, run_at_exit in _hooks:
47 def add_file_to_unlink(file):
48 """Registers 'file' to be unlinked when the program terminates via
49 sys.exit() or a fatal signal."""
53 add_hook(_unlink_files, _cancel_files, True)
56 def remove_file_to_unlink(file):
57 """Unregisters 'file' from being unlinked when the program terminates via
58 sys.exit() or a fatal signal."""
62 def unlink_file_now(file):
63 """Like fatal_signal_remove_file_to_unlink(), but also unlinks 'file'.
64 Returns 0 if successful, otherwise a positive errno value."""
67 logging.warning("could not unlink \"%s\" (%s)"
68 % (file, os.strerror(error)))
69 remove_file_to_unlink(file)
89 def _signal_handler(signr, frame):
92 # Re-raise the signal with the default handling so that the program
93 # termination status reflects that we were killed by this signal.
94 signal.signal(signr, signal.SIG_DFL)
95 os.kill(os.getpid(), signr)
97 def _atexit_handler():
101 def _call_hooks(signr):
107 for hook, cancel, run_at_exit in _hooks:
108 if signr != 0 or run_at_exit:
117 for signr in (signal.SIGTERM, signal.SIGINT,
118 signal.SIGHUP, signal.SIGALRM):
119 if signal.getsignal(signr) == signal.SIG_DFL:
120 signal.signal(signr, _signal_handler)
121 atexit.register(_atexit_handler)