Python signal.SIG_DFL Examples

The following are 30 code examples of signal.SIG_DFL(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module signal , or try the search function .
Example #1
Source File: util.py    From wechat-alfred-workflow with MIT License 7 votes vote down vote up
def __call__(self, *args, **kwargs):
        """Trap ``SIGTERM`` and call wrapped function."""
        self._caught_signal = None
        # Register handler for SIGTERM, then call `self.func`
        self.old_signal_handler = signal.getsignal(signal.SIGTERM)
        signal.signal(signal.SIGTERM, self.signal_handler)

        self.func(*args, **kwargs)

        # Restore old signal handler
        signal.signal(signal.SIGTERM, self.old_signal_handler)

        # Handle any signal caught during execution
        if self._caught_signal is not None:
            signum, frame = self._caught_signal
            if callable(self.old_signal_handler):
                self.old_signal_handler(signum, frame)
            elif self.old_signal_handler == signal.SIG_DFL:
                sys.exit(0) 
Example #2
Source File: _utils.py    From cotyledon with Apache License 2.0 7 votes vote down vote up
def __init__(self):
        # Setup signal fd, this allows signal to behave correctly
        if os.name == 'posix':
            self.signal_pipe_r, self.signal_pipe_w = os.pipe()
            self._set_nonblock(self.signal_pipe_r)
            self._set_nonblock(self.signal_pipe_w)
            signal.set_wakeup_fd(self.signal_pipe_w)

        self._signals_received = collections.deque()

        signal.signal(signal.SIGINT, signal.SIG_DFL)
        if os.name == 'posix':
            signal.signal(signal.SIGCHLD, signal.SIG_DFL)
            signal.signal(signal.SIGTERM, self._signal_catcher)
            signal.signal(signal.SIGALRM, self._signal_catcher)
            signal.signal(signal.SIGHUP, self._signal_catcher)
        else:
            # currently a noop on window...
            signal.signal(signal.SIGTERM, self._signal_catcher)
            # FIXME(sileht): should allow to catch signal CTRL_BREAK_EVENT,
            # but we to create the child process with CREATE_NEW_PROCESS_GROUP
            # to make this work, so current this is a noop for later fix
            signal.signal(signal.SIGBREAK, self._signal_catcher) 
Example #3
Source File: util.py    From alfred-brightness with MIT License 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        """Trap ``SIGTERM`` and call wrapped function."""
        self._caught_signal = None
        # Register handler for SIGTERM, then call `self.func`
        self.old_signal_handler = signal.getsignal(signal.SIGTERM)
        signal.signal(signal.SIGTERM, self.signal_handler)

        self.func(*args, **kwargs)

        # Restore old signal handler
        signal.signal(signal.SIGTERM, self.old_signal_handler)

        # Handle any signal caught during execution
        if self._caught_signal is not None:
            signum, frame = self._caught_signal
            if callable(self.old_signal_handler):
                self.old_signal_handler(signum, frame)
            elif self.old_signal_handler == signal.SIG_DFL:
                sys.exit(0) 
Example #4
Source File: workflow.py    From Gank-Alfred-Workflow with MIT License 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        self._caught_signal = None
        # Register handler for SIGTERM, then call `self.func`
        self.old_signal_handler = signal.getsignal(signal.SIGTERM)
        signal.signal(signal.SIGTERM, self.signal_handler)

        self.func(*args, **kwargs)

        # Restore old signal handler
        signal.signal(signal.SIGTERM, self.old_signal_handler)

        # Handle any signal caught during execution
        if self._caught_signal is not None:
            signum, frame = self._caught_signal
            if callable(self.old_signal_handler):
                self.old_signal_handler(signum, frame)
            elif self.old_signal_handler == signal.SIG_DFL:
                sys.exit(0) 
Example #5
Source File: workflow.py    From Gank-Alfred-Workflow with MIT License 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        self._caught_signal = None
        # Register handler for SIGTERM, then call `self.func`
        self.old_signal_handler = signal.getsignal(signal.SIGTERM)
        signal.signal(signal.SIGTERM, self.signal_handler)

        self.func(*args, **kwargs)

        # Restore old signal handler
        signal.signal(signal.SIGTERM, self.old_signal_handler)

        # Handle any signal caught during execution
        if self._caught_signal is not None:
            signum, frame = self._caught_signal
            if callable(self.old_signal_handler):
                self.old_signal_handler(signum, frame)
            elif self.old_signal_handler == signal.SIG_DFL:
                sys.exit(0) 
Example #6
Source File: main.py    From raspiblitz with MIT License 6 votes vote down vote up
def main():
    # make sure CTRL+C works
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    description = """BlitzTUI - the Touch-User-Interface for the RaspiBlitz project

Keep on stacking SATs..! :-D"""

    parser = argparse.ArgumentParser(description=description, formatter_class=RawTextHelpFormatter)
    parser.add_argument("-V", "--version",
                        help="print version", action="version",
                        version=__version__)

    parser.add_argument('-d', '--debug', help="enable debug logging", action="store_true")

    # parse args
    args = parser.parse_args()

    if args.debug:
        setup_logging(log_level="DEBUG")
    else:
        setup_logging()

    log.info("Starting BlitzTUI v{}".format(__version__))

    # initialize app
    app = QApplication(sys.argv)

    w = AppWindow()
    w.show()

    # run app
    sys.exit(app.exec_()) 
Example #7
Source File: workflow.py    From Quiver-alfred with MIT License 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        self._caught_signal = None
        # Register handler for SIGTERM, then call `self.func`
        self.old_signal_handler = signal.getsignal(signal.SIGTERM)
        signal.signal(signal.SIGTERM, self.signal_handler)

        self.func(*args, **kwargs)

        # Restore old signal handler
        signal.signal(signal.SIGTERM, self.old_signal_handler)

        # Handle any signal caught during execution
        if self._caught_signal is not None:
            signum, frame = self._caught_signal
            if callable(self.old_signal_handler):
                self.old_signal_handler(signum, frame)
            elif self.old_signal_handler == signal.SIG_DFL:
                sys.exit(0) 
Example #8
Source File: signals.py    From jawfish with MIT License 6 votes vote down vote up
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler 
Example #9
Source File: worker.py    From PumpkinLB with GNU General Public License v3.0 6 votes vote down vote up
def closeConnections(self):
        try:
            self.workerSocket.shutdown(socket.SHUT_RDWR)
        except:
            pass
        try:
            self.workerSocket.close()
        except:
            pass
        try:
            self.clientSocket.shutdown(socket.SHUT_RDWR)
        except:
            pass
        try:
            self.clientSocket.close()
        except:
            pass
        signal.signal(signal.SIGTERM, signal.SIG_DFL) 
Example #10
Source File: util.py    From gist-alfred with MIT License 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        """Trap ``SIGTERM`` and call wrapped function."""
        self._caught_signal = None
        # Register handler for SIGTERM, then call `self.func`
        self.old_signal_handler = signal.getsignal(signal.SIGTERM)
        signal.signal(signal.SIGTERM, self.signal_handler)

        self.func(*args, **kwargs)

        # Restore old signal handler
        signal.signal(signal.SIGTERM, self.old_signal_handler)

        # Handle any signal caught during execution
        if self._caught_signal is not None:
            signum, frame = self._caught_signal
            if callable(self.old_signal_handler):
                self.old_signal_handler(signum, frame)
            elif self.old_signal_handler == signal.SIG_DFL:
                sys.exit(0) 
Example #11
Source File: plugins.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def unsubscribe(self):
        """Unsubscribe self.handlers from signals."""
        for signum, handler in self._previous_handlers.items():
            signame = self.signals[signum]

            if handler is None:
                self.bus.log('Restoring %s handler to SIG_DFL.' % signame)
                handler = _signal.SIG_DFL
            else:
                self.bus.log('Restoring %s handler %r.' % (signame, handler))

            try:
                our_handler = _signal.signal(signum, handler)
                if our_handler is None:
                    self.bus.log('Restored old %s handler %r, but our '
                                 'handler was not registered.' %
                                 (signame, handler), level=30)
            except ValueError:
                self.bus.log('Unable to restore %s handler %r.' %
                             (signame, handler), level=40, traceback=True) 
Example #12
Source File: signal_handler.py    From BiblioPixel with MIT License 6 votes vote down vote up
def context(**handlers):
    signals = {}

    def handler(signum, frame):
        signame = SIGNAL_NAMES[signum]
        signals[signame] = True
        handler = handlers[signame]
        handler()

    def set_all(handler):
        for signame in handlers:
            if signame in SIGNAL_NUMBERS:  # Windows doesn't have all signals
                signal.signal(SIGNAL_NUMBERS[signame], handler)

    set_all(handler)
    try:
        yield signals

    finally:
        set_all(signal.SIG_DFL) 
Example #13
Source File: test_sigchld.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        """
        Save the current SIGCHLD handler as reported by L{signal.signal} and
        the current file descriptor registered with L{installHandler}.
        """
        handler = signal.getsignal(signal.SIGCHLD)
        if handler != signal.SIG_DFL:
            self.signalModuleHandler = handler
            signal.signal(signal.SIGCHLD, signal.SIG_DFL)
        else:
            self.signalModuleHandler = None

        self.oldFD = installHandler(-1)

        if self.signalModuleHandler is not None and self.oldFD != -1:
            msg("Previous test didn't clean up after its SIGCHLD setup: %r %r"
                % (self.signalModuleHandler, self.oldFD)) 
Example #14
Source File: _signals.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def installHandler(fd):
    """
    Install a signal handler which will write a byte to C{fd} when
    I{SIGCHLD} is received.

    This is implemented by installing a SIGCHLD handler that does nothing,
    setting the I{SIGCHLD} handler as not allowed to interrupt system calls,
    and using L{signal.set_wakeup_fd} to do the actual writing.

    @param fd: The file descriptor to which to write when I{SIGCHLD} is
        received.
    @type fd: C{int}
    """
    if fd == -1:
        signal.signal(signal.SIGCHLD, signal.SIG_DFL)
    else:
        def noopSignalHandler(*args):
            pass
        signal.signal(signal.SIGCHLD, noopSignalHandler)
        signal.siginterrupt(signal.SIGCHLD, False)
    return signal.set_wakeup_fd(fd) 
Example #15
Source File: archive.py    From bob with GNU General Public License v3.0 6 votes vote down vote up
def _downloadLocalFile(self, key, suffix):
        # Set default signal handler so that KeyboardInterrupt is raised.
        # Needed to gracefully handle ctrl+c.
        signal.signal(signal.SIGINT, signal.default_int_handler)

        try:
            with self._openDownloadFile(key, suffix) as (name, fileobj):
                ret = readFileOrHandle(name, fileobj)
            return (ret, None, None)
        except ArtifactNotFoundError:
            return (None, "not found", WARNING)
        except ArtifactDownloadError as e:
            return (None, e.reason, WARNING)
        except BuildError as e:
            raise
        except OSError as e:
            raise BuildError("Cannot download file: " + str(e))
        finally:
            # Restore signals to default so that Ctrl+C kills process. Needed
            # to prevent ugly backtraces when user presses ctrl+c.
            signal.signal(signal.SIGINT, signal.SIG_DFL) 
Example #16
Source File: archive.py    From bob with GNU General Public License v3.0 6 votes vote down vote up
def _uploadPackage(self, buildId, suffix, audit, content):
        # Set default signal handler so that KeyboardInterrupt is raised.
        # Needed to gracefully handle ctrl+c.
        signal.signal(signal.SIGINT, signal.default_int_handler)

        try:
            with self._openUploadFile(buildId, suffix) as (name, fileobj):
                pax = { 'bob-archive-vsn' : "1" }
                with gzip.open(name or fileobj, 'wb', 6) as gzf:
                    with tarfile.open(name, "w", fileobj=gzf,
                                      format=tarfile.PAX_FORMAT, pax_headers=pax) as tar:
                        tar.add(audit, "meta/" + os.path.basename(audit))
                        tar.add(content, arcname="content")
        except ArtifactExistsError:
            return ("skipped ({} exists in archive)".format(content), SKIPPED)
        except (ArtifactUploadError, tarfile.TarError, OSError) as e:
            if self.__ignoreErrors:
                return ("error ("+str(e)+")", ERROR)
            else:
                raise BuildError("Cannot upload artifact: " + str(e))
        finally:
            # Restore signals to default so that Ctrl+C kills process. Needed
            # to prevent ugly backtraces when user presses ctrl+c.
            signal.signal(signal.SIGINT, signal.SIG_DFL)
        return ("ok", EXECUTED) 
Example #17
Source File: archive.py    From bob with GNU General Public License v3.0 6 votes vote down vote up
def _uploadLocalFile(self, key, suffix, content):
        # Set default signal handler so that KeyboardInterrupt is raised.
        # Needed to gracefully handle ctrl+c.
        signal.signal(signal.SIGINT, signal.default_int_handler)

        try:
            with self._openUploadFile(key, suffix) as (name, fileobj):
                writeFileOrHandle(name, fileobj, content)
        except ArtifactExistsError:
            return ("skipped (exists in archive)", SKIPPED)
        except (ArtifactUploadError, OSError) as e:
            if self.__ignoreErrors:
                return ("error ("+str(e)+")", ERROR)
            else:
                raise BuildError("Cannot upload file: " + str(e))
        finally:
            # Restore signals to default so that Ctrl+C kills process. Needed
            # to prevent ugly backtraces when user presses ctrl+c.
            signal.signal(signal.SIGINT, signal.SIG_DFL)
        return ("ok", EXECUTED) 
Example #18
Source File: signals.py    From oss-ftp with MIT License 6 votes vote down vote up
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler 
Example #19
Source File: signals.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, (int, long)):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler 
Example #20
Source File: test_signal.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_signal_signal(self):
        WORKING_CASES = SUPPORTED_SIGNALS + [6]
        WEIRD_CASES = {
                    6: None,
                    2: signal.default_int_handler}
        for x in WORKING_CASES:
            #Ideal handler signature
            def a(signum, frame):
                return x
            
            ret_val = signal.signal(x, a)
            if x not in WEIRD_CASES.keys():
                self.assertEqual(ret_val, signal.SIG_DFL)
            else:
                self.assertEqual(ret_val, WEIRD_CASES[x])
            self.assertEqual(a, signal.getsignal(x))
            
        #Strange handler signatures
        class KNew(object):
            def __call__(self, *args, **kwargs):
                pass
        
        a = KNew()
        ret_val = signal.signal(signal.SIGBREAK, a)
        self.assertEqual(a, signal.getsignal(signal.SIGBREAK)) 
Example #21
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        """
        Run guest main thread
        """
        global virt
        global exiting
        virt = VirtioGuestPosix()
        slave = Thread(target=worker, args=(virt,))
        slave.start()
        signal.signal(signal.SIGUSR1, sigusr_handler)
        signal.signal(signal.SIGALRM, sigusr_handler)
        while not exiting:
            signal.alarm(1)
            signal.pause()
            catch = virt.catching_signal()
            if catch:
                signal.signal(signal.SIGIO, virt)
            elif catch is False:
                signal.signal(signal.SIGIO, signal.SIG_DFL)
            if catch is not None:
                virt.use_config.set()
        print("PASS: guest_exit")
        sys.exit(0) 
Example #22
Source File: signals.py    From BinderFilter with MIT License 6 votes vote down vote up
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler 
Example #23
Source File: common.py    From pwtools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def permit_sigpipe():
    """Helper for subprocess.Popen(). Handle SIGPIPE. To be used as preexec_fn.

    Notes
    -----
    Things like::

        >>> cmd = r"grep pattern /path/to/very_big_file | head -n1"
        >>> pp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
        ...                       stderr=subprocess.PIPE)
        >>> out,err = pp.communicate()

    sometimes end with a broken pipe error: "grep: writing output: Broken
    pipe". They run fine at the bash prompt, while failing with Popen. The
    reason is that they actually "kind of" fail in the shell too, namely,
    SIGPIPE [1,2]. This can be seen by runing the call in strace "$ strace grep
    ...". Popen chokes on that. The solution is to ignore SIGPIPE.

    References
    ----------
    .. [1] http://mail.python.org/pipermail/tutor/2007-October/058042.html
    .. [2] http://article.gmane.org/gmane.comp.python.devel/88798/
    """
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)


# XXX The error handling is not safe since we raise the exception only when
# stderr is not empty w/o checking the retcode. This fails if we do
# backtick('dhwjqdhwjwqdk 2>/dev/null'). This may have been a design decision
# in order to deal with flaky shell commands. But we should never use that in
# tests. 
Example #24
Source File: spin.py    From pipenv with MIT License 5 votes vote down vote up
def _register_signal_handlers(self):
        # type: () -> None
        # SIGKILL cannot be caught or ignored, and the receiving
        # process cannot perform any clean-up upon receiving this
        # signal.
        try:
            if signal.SIGKILL in self._sigmap.keys():
                raise ValueError(
                    "Trying to set handler for SIGKILL signal. "
                    "SIGKILL cannot be cought or ignored in POSIX systems."
                )
        except AttributeError:
            pass

        for sig, sig_handler in self._sigmap.items():
            # A handler for a particular signal, once set, remains
            # installed until it is explicitly reset. Store default
            # signal handlers for subsequent reset at cleanup phase.
            dfl_handler = signal.getsignal(sig)
            self._dfl_sigmap[sig] = dfl_handler

            # ``signal.SIG_DFL`` and ``signal.SIG_IGN`` are also valid
            # signal handlers and are not callables.
            if callable(sig_handler):
                # ``signal.signal`` accepts handler function which is
                # called with two arguments: signal number and the
                # interrupted stack frame. ``functools.partial`` solves
                # the problem of passing spinner instance into the handler
                # function.
                sig_handler = functools.partial(sig_handler, spinner=self)

            signal.signal(sig, sig_handler) 
Example #25
Source File: ioloop.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def set_blocking_signal_threshold(self, seconds, action):
        if not hasattr(signal, "setitimer"):
            gen_log.error("set_blocking_signal_threshold requires a signal module "
                          "with the setitimer method")
            return
        self._blocking_signal_threshold = seconds
        if seconds is not None:
            signal.signal(signal.SIGALRM,
                          action if action is not None else signal.SIG_DFL) 
Example #26
Source File: pipeline.py    From Comparative-Annotation-Toolkit with Apache License 2.0 5 votes vote down vote up
def __doChildStart(self):
        "guts of start child process"
        self.statusPipe.postForkChild()
        _setPgid(os.getpid(), self.dag.pgid if (self.dag.pgid is not None) else os.getpid())
        cmd = self.__buildCmd()
        self.__stdioSetup(self.stdin, 0)
        self.__stdioSetup(self.stdout, 1)
        self.__stdioSetup(self.stderr, 2)
        self.__closeFiles()
        signal.signal(signal.SIGPIPE, signal.SIG_DFL)
        os.execvp(cmd[0], cmd) 
Example #27
Source File: ioloop.py    From Computable with MIT License 5 votes vote down vote up
def set_blocking_signal_threshold(self, seconds, action):
        if not hasattr(signal, "setitimer"):
            gen_log.error("set_blocking_signal_threshold requires a signal module "
                          "with the setitimer method")
            return
        self._blocking_signal_threshold = seconds
        if seconds is not None:
            signal.signal(signal.SIGALRM,
                          action if action is not None else signal.SIG_DFL) 
Example #28
Source File: ioloop.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def set_blocking_signal_threshold(self, seconds, action):
        if not hasattr(signal, "setitimer"):
            gen_log.error("set_blocking_signal_threshold requires a signal module "
                          "with the setitimer method")
            return
        self._blocking_signal_threshold = seconds
        if seconds is not None:
            signal.signal(signal.SIGALRM,
                          action if action is not None else signal.SIG_DFL) 
Example #29
Source File: console.py    From eyeD3 with GNU General Public License v3.0 5 votes vote down vote up
def __exit__(self, exc_type, exc_value, traceback):
        if not self._silent:
            if exc_type is None:
                self.update(self._total)
            self._file.write('\n')
            self._file.flush()
            if self._signal_set:
                signal.signal(signal.SIGWINCH, signal.SIG_DFL) 
Example #30
Source File: backend_qt4.py    From Computable with MIT License 5 votes vote down vote up
def mainloop(self):
        # allow KeyboardInterrupt exceptions to close the plot window.
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        QtGui.qApp.exec_()