Save and restore signal handlers. This class is only able to save/restore signal handlers registered by the Python signal module: see bpo-13285 for "external" signal handlers.
| 2180 | |
| 2181 | |
| 2182 | class SaveSignals: |
| 2183 | """ |
| 2184 | Save and restore signal handlers. |
| 2185 | |
| 2186 | This class is only able to save/restore signal handlers registered |
| 2187 | by the Python signal module: see bpo-13285 for "external" signal |
| 2188 | handlers. |
| 2189 | """ |
| 2190 | |
| 2191 | def __init__(self): |
| 2192 | import signal |
| 2193 | self.signal = signal |
| 2194 | self.signals = signal.valid_signals() |
| 2195 | # SIGKILL and SIGSTOP signals cannot be ignored nor caught |
| 2196 | for signame in ('SIGKILL', 'SIGSTOP'): |
| 2197 | try: |
| 2198 | signum = getattr(signal, signame) |
| 2199 | except AttributeError: |
| 2200 | continue |
| 2201 | self.signals.remove(signum) |
| 2202 | self.handlers = {} |
| 2203 | |
| 2204 | def save(self): |
| 2205 | for signum in self.signals: |
| 2206 | handler = self.signal.getsignal(signum) |
| 2207 | if handler is None: |
| 2208 | # getsignal() returns None if a signal handler was not |
| 2209 | # registered by the Python signal module, |
| 2210 | # and the handler is not SIG_DFL nor SIG_IGN. |
| 2211 | # |
| 2212 | # Ignore the signal: we cannot restore the handler. |
| 2213 | continue |
| 2214 | self.handlers[signum] = handler |
| 2215 | |
| 2216 | def restore(self): |
| 2217 | for signum, handler in self.handlers.items(): |
| 2218 | self.signal.signal(signum, handler) |
| 2219 | |
| 2220 | |
| 2221 | def with_pymalloc(): |