Python signal.SIGTSTP Examples

The following are 25 code examples of signal.SIGTSTP(). 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: compat.py    From bash-lambda-layer with MIT License 7 votes vote down vote up
def ignore_user_entered_signals():
    """
    Ignores user entered signals to avoid process getting killed.
    """
    if is_windows:
        signal_list = [signal.SIGINT]
    else:
        signal_list = [signal.SIGINT, signal.SIGQUIT, signal.SIGTSTP]
    actual_signals = []
    for user_signal in signal_list:
        actual_signals.append(signal.signal(user_signal, signal.SIG_IGN))
    try:
        yield
    finally:
        for sig, user_signal in enumerate(signal_list):
            signal.signal(user_signal, actual_signals[sig]) 
Example #2
Source File: worker.py    From ndkale with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _cleanup_worker(self, signum, frame):
        """Handle cleanup when the process is sent a signal.

        This will handle releasing tasks in flight and deleting tasks that have
        been completed.
        """
        logger.info('Process sent signal %d. Cleaning up tasks...' % signum)

        num_completed, num_incomplete = self._release_batch()

        # When the process is suspended we release tasks and then return to the
        # main loop.
        if signum == signal.SIGTSTP:
            self._on_sigtstp(num_completed, num_incomplete)
            return
        else:
            # Allow the client of this library to do any setup before
            # shutting down the worker.
            settings.ON_WORKER_SHUTDOWN()
            self._on_shutdown(num_completed, num_incomplete)
            sys.exit(0) 
Example #3
Source File: proxies_signals_test.py    From dumb-init with MIT License 6 votes vote down vote up
def test_default_rewrites_can_be_overriden_with_setsid_enabled():
    """In setsid mode, dumb-init should allow overwriting the default
    rewrites (but still suspend itself).
    """
    rewrite_map = {
        signal.SIGTTIN: signal.SIGTERM,
        signal.SIGTTOU: signal.SIGINT,
        signal.SIGTSTP: signal.SIGHUP,
    }
    with print_signals(_rewrite_map_to_args(rewrite_map)) as (proc, _):
        for send, expect_receive in rewrite_map.items():
            assert process_state(proc.pid) in ['running', 'sleeping']
            proc.send_signal(send)

            assert proc.stdout.readline() == '{}\n'.format(expect_receive).encode('ascii')
            os.waitpid(proc.pid, os.WUNTRACED)
            assert process_state(proc.pid) == 'stopped'

            proc.send_signal(signal.SIGCONT)
            assert proc.stdout.readline() == '{}\n'.format(signal.SIGCONT).encode('ascii')
            assert process_state(proc.pid) in ['running', 'sleeping'] 
Example #4
Source File: interface.py    From android_universal with MIT License 6 votes vote down vote up
def suspend_to_background(self, suspend_group=True):
        """
        (Not thread safe -- to be called from inside the key bindings.)
        Suspend process.

        :param suspend_group: When true, suspend the whole process group.
            (This is the default, and probably what you want.)
        """
        # Only suspend when the opperating system supports it.
        # (Not on Windows.)
        if hasattr(signal, 'SIGTSTP'):
            def run():
                # Send `SIGSTP` to own process.
                # This will cause it to suspend.

                # Usually we want the whole process group to be suspended. This
                # handles the case when input is piped from another process.
                if suspend_group:
                    os.kill(0, signal.SIGTSTP)
                else:
                    os.kill(os.getpid(), signal.SIGTSTP)

            self.run_in_terminal(run) 
Example #5
Source File: AIWIBoardContext.py    From RPiNWR with GNU General Public License v3.0 6 votes vote down vote up
def __enter__(self):
        # Make sure to cleanup GPIO afterward
        if not self.__signals_trapped:
            self.__signals_trapped = True
            for sig in [signal.SIGQUIT, signal.SIGTERM, signal.SIGTSTP]:
                if hasattr(signal.getsignal(sig), '__call__'):
                    deleg = signal.getsignal(sig)

                    def delegate(signum, stack):
                        self.__exit__(None, None, None)
                        deleg(signum, stack)

                    signal.signal(sig, delegate)
                else:
                    def delegate(signum, stack):
                        self.__exit__(None, None, None)

                    signal.signal(sig, delegate)
        return self 
Example #6
Source File: daemon.py    From virt-who with GNU General Public License v2.0 6 votes vote down vote up
def make_default_signal_map():
    """ Make the default signal map for this system.

        The signals available differ by system. The map will not
        contain any signals not defined on the running system.

        """
    name_map = {
        'SIGTSTP': None,
        'SIGTTIN': None,
        'SIGTTOU': None,
        'SIGTERM': 'terminate',
    }
    signal_map = dict(
        (getattr(signal, name), target)
        for (name, target) in name_map.items()
        if hasattr(signal, name))

    return signal_map 
Example #7
Source File: daemon.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def make_default_signal_map():
    """ Make the default signal map for this system.

        The signals available differ by system. The map will not
        contain any signals not defined on the running system.

        """
    name_map = {
        'SIGTSTP': None,
        'SIGTTIN': None,
        'SIGTTOU': None,
        'SIGTERM': 'terminate',
        }
    signal_map = dict(
        (getattr(signal, name), target)
        for (name, target) in name_map.items()
        if hasattr(signal, name))

    return signal_map 
Example #8
Source File: __init__.py    From service with MIT License 6 votes vote down vote up
def __init__(self, name, pid_dir='/var/run', signals=None):
        """
        Constructor.

        ``name`` is a string that identifies the daemon. The name is
        used for the name of the daemon process, the PID file and for
        the messages to syslog.

        ``pid_dir`` is the directory in which the PID file is stored.

        ``signals`` list of operating signals, that should be available
        for use with :py:meth:`.send_signal`, :py:meth:`.got_signal`,
        :py:meth:`.wait_for_signal`, and :py:meth:`.check_signal`. Note
        that SIGTERM is always supported, and that SIGTTIN, SIGTTOU, and
        SIGTSTP are never supported.
        """
        self.name = name
        self.pid_file = _PIDFile(os.path.join(pid_dir, name + '.pid'))
        self._signal_events = {int(s): threading.Event()
                               for s in ((signals or []) + [signal.SIGTERM])}
        self.logger = logging.getLogger(name)
        if not self.logger.handlers:
            self.logger.addHandler(logging.NullHandler())
        self.files_preserve = [] 
Example #9
Source File: agent.py    From automl-phase-2 with MIT License 6 votes vote down vote up
def save(self):
        """Save important things to file"""
        self.flag.value = 2

        logger.info("Saving")
        # Ignore sigtstp messages from now on:
        signal.signal(signal.SIGTSTP, self.signal_ignore)

        # Saving only happens on the first CPU
        p = psutil.Process()
        current_cpus = p.cpu_affinity()
        if len(current_cpus) > 1:
            p.cpu_affinity([current_cpus[0]])

        # Save children
        self.save_children(save_timeout=300)

        # Save myself
        with open(self.save_file, 'wb') as pickle_file:
            pickle.dump(self, pickle_file, pickle.HIGHEST_PROTOCOL)

        logger.info("Completed saving")
        self.flag.value = 3 
Example #10
Source File: agent.py    From automl-phase-2 with MIT License 6 votes vote down vote up
def pause_children(self, names=None):
        # send pause signal to alive children
        if names is None:
            names = self.conns_from_children.keys()

        logger.debug("Pausing %s", str(names))

        for name in names:
            assert name in self.child_states  # check it's a real child
            proc = self.child_processes[name]
            if proc.is_alive():
                try:
                    process = psutil.Process(pid=proc.pid)
                    try:
                        for child in process.children(recursive=True):
                            try:
                                child.send_signal(signal.SIGTSTP)
                            except (psutil.NoSuchProcess, psutil.AccessDenied, IOError):
                                pass
                    except (psutil.NoSuchProcess, psutil.AccessDenied, IOError) as e:
                        logger.warn("Error %s getting children for pause for child %s", e.strerror, name)
                    process.send_signal(signal.SIGTSTP)
                    logger.info("Paused %s", name)
                except (psutil.NoSuchProcess, psutil.AccessDenied, IOError):  # child may have terminated
                    pass 
Example #11
Source File: test_screen.py    From asciimatics with Apache License 2.0 5 votes vote down vote up
def test_catch_exceptions(self):
        """
        Check that we can catch exceptions (e.g. for ctrl-c).
        """
        def internal_checks(screen):
            # Not much we can do here as refresh will draw to a screen we can't
            # query. Check that we don't hit an Exception on refresh().
            if sys.platform == "win32":
                # Strictly speaking, this doesn't test catching ctrl-c as
                # it isn't possible to trigger the control handler (even if
                # we don't catch interrupts).  Still a good basic check for
                # input, though.
                event = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
                event.Char = u"\03"
                event.KeyDown = 1
                event.RepeatCount = 1
                event.ControlKeyState = win32con.LEFT_CTRL_PRESSED
                event.VirtualKeyCode = 67
                event.VirtualScanCode = 46
                screen._stdin.WriteConsoleInput([event])
                event.KeyDown = 0
                screen._stdin.WriteConsoleInput([event])
                ch = screen.get_event()
                self.assertEqual(ch.key_code, 3)
                self.assertIsNone(screen.get_event())
            else:
                # Check Ctrl-c (and no other input)
                os.kill(os.getpid(), signal.SIGINT)
                ch = screen.get_event()
                self.assertEqual(ch.key_code, 3)
                self.assertIsNone(screen.get_event())

                # Check Ctrl-z (and no other input)
                os.kill(os.getpid(), signal.SIGTSTP)
                ch = screen.get_event()
                self.assertEqual(ch.key_code, 26)
                self.assertIsNone(screen.get_event())

        Screen.wrapper(internal_checks, height=15, catch_interrupt=True) 
Example #12
Source File: conch.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def handleInput(self, char):
        if char in (b'\n', b'\r'):
            self.escapeMode = 1
            self.write(char)
        elif self.escapeMode == 1 and char == options['escape']:
            self.escapeMode = 2
        elif self.escapeMode == 2:
            self.escapeMode = 1  # So we can chain escapes together
            if char == b'.':  # Disconnect
                log.msg('disconnecting from escape')
                stopConnection()
                return
            elif char == b'\x1a':  # ^Z, suspend
                def _():
                    _leaveRawMode()
                    sys.stdout.flush()
                    sys.stdin.flush()
                    os.kill(os.getpid(), signal.SIGTSTP)
                    _enterRawMode()
                reactor.callLater(0, _)
                return
            elif char == b'R':  # Rekey connection
                log.msg('rekeying connection')
                self.conn.transport.sendKexInit()
                return
            elif char == b'#':  # Display connections
                self.stdio.write(
                    b'\r\nThe following connections are open:\r\n')
                channels = self.conn.channels.keys()
                channels.sort()
                for channelId in channels:
                    self.stdio.write(networkString('  #{} {}\r\n'.format(
                                     channelId,
                                     self.conn.channels[channelId])))
                return
            self.write(b'~' + char)
        else:
            self.escapeMode = 0
            self.write(char) 
Example #13
Source File: console_service.py    From pyethapp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, app):
        super(Console, self).__init__(app)
        self.interrupt = Event()
        gevent.signal(signal.SIGTSTP, self.interrupt.set)
        self.console_locals = [] 
Example #14
Source File: pipeline.py    From bifrost with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def shutdown_on_signals(self, signals=None):
        if signals is None:
            signals = [signal.SIGHUP,
                       signal.SIGINT,
                       signal.SIGQUIT,
                       signal.SIGTERM,
                       signal.SIGTSTP]
        for sig in signals:
            signal.signal(sig, self._handle_signal_shutdown) 
Example #15
Source File: screen.py    From aws-elastic-beanstalk-cli with Apache License 2.0 5 votes vote down vote up
def _catch_interrupt(signal_no, frame):
            """
            SIGINT handler.  We ignore the signal and frame info passed in.
            """
            # Stop pep-8 shouting at me for unused params I can't control.
            del frame

            # The OS already caught the ctrl-c, so inject it now for the next
            # input.
            if signal_no == signal.SIGINT:
                curses.ungetch(3)
            elif signal_no == signal.SIGTSTP:
                curses.ungetch(26)
            return 
Example #16
Source File: conch.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def handleInput(self, char):
        #log.msg('handling %s' % repr(char))
        if char in ('\n', '\r'):
            self.escapeMode = 1
            self.write(char)
        elif self.escapeMode == 1 and char == options['escape']:
            self.escapeMode = 2
        elif self.escapeMode == 2:
            self.escapeMode = 1 # so we can chain escapes together
            if char == '.': # disconnect
                log.msg('disconnecting from escape')
                stopConnection()
                return
            elif char == '\x1a': # ^Z, suspend
                def _():
                    _leaveRawMode()
                    sys.stdout.flush()
                    sys.stdin.flush()
                    os.kill(os.getpid(), signal.SIGTSTP)
                    _enterRawMode()
                reactor.callLater(0, _)
                return
            elif char == 'R': # rekey connection
                log.msg('rekeying connection')
                self.conn.transport.sendKexInit()
                return
            elif char == '#': # display connections
                self.stdio.write('\r\nThe following connections are open:\r\n')
                channels = self.conn.channels.keys()
                channels.sort()
                for channelId in channels:
                    self.stdio.write('  #%i %s\r\n' % (channelId, str(self.conn.channels[channelId])))
                return
            self.write('~' + char)
        else:
            self.escapeMode = 0
            self.write(char) 
Example #17
Source File: conch.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def handleInput(self, char):
        #log.msg('handling %s' % repr(char))
        if char in ('\n', '\r'):
            self.escapeMode = 1
            self.write(char)
        elif self.escapeMode == 1 and char == options['escape']:
            self.escapeMode = 2
        elif self.escapeMode == 2:
            self.escapeMode = 1 # so we can chain escapes together
            if char == '.': # disconnect
                log.msg('disconnecting from escape')
                stopConnection()
                return
            elif char == '\x1a': # ^Z, suspend
                def _():
                    _leaveRawMode()
                    sys.stdout.flush()
                    sys.stdin.flush()
                    os.kill(os.getpid(), signal.SIGTSTP)
                    _enterRawMode()
                reactor.callLater(0, _)
                return
            elif char == 'R': # rekey connection
                log.msg('rekeying connection')
                self.conn.transport.sendKexInit()
                return
            elif char == '#': # display connections
                self.stdio.write('\r\nThe following connections are open:\r\n')
                channels = self.conn.channels.keys()
                channels.sort()
                for channelId in channels:
                    self.stdio.write('  #%i %s\r\n' % (channelId, str(self.conn.channels[channelId])))
                return
            self.write('~' + char)
        else:
            self.escapeMode = 0
            self.write(char) 
Example #18
Source File: conch.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def handleInput(self, char):
        #log.msg('handling %s' % repr(char))
        if char in ('\n', '\r'):
            self.escapeMode = 1
            self.write(char)
        elif self.escapeMode == 1 and char == options['escape']:
            self.escapeMode = 2
        elif self.escapeMode == 2:
            self.escapeMode = 1 # so we can chain escapes together
            if char == '.': # disconnect
                log.msg('disconnecting from escape')
                stopConnection()
                return
            elif char == '\x1a': # ^Z, suspend
                def _():
                    _leaveRawMode()
                    sys.stdout.flush()
                    sys.stdin.flush()
                    os.kill(os.getpid(), signal.SIGTSTP)
                    _enterRawMode()
                reactor.callLater(0, _)
                return
            elif char == 'R': # rekey connection
                log.msg('rekeying connection')
                self.conn.transport.sendKexInit()
                return
            elif char == '#': # display connections
                self.stdio.write('\r\nThe following connections are open:\r\n')
                channels = self.conn.channels.keys()
                channels.sort()
                for channelId in channels:
                    self.stdio.write('  #%i %s\r\n' % (channelId, str(self.conn.channels[channelId])))
                return
            self.write('~' + char)
        else:
            self.escapeMode = 0
            self.write(char) 
Example #19
Source File: screen.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def _catch_interrupt(signal_no, frame):
            """
            SIGINT handler.  We ignore the signal and frame info passed in.
            """
            # Stop pep-8 shouting at me for unused params I can't control.
            del frame

            # The OS already caught the ctrl-c, so inject it now for the next
            # input.
            if signal_no == signal.SIGINT:
                curses.ungetch(3)
            elif signal_no == signal.SIGTSTP:
                curses.ungetch(26)
            return 
Example #20
Source File: posix.py    From pymux with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _process(self, data_buffer):
        """
        Handle incoming packet from server.
        """
        packet = json.loads(data_buffer.decode('utf-8'))

        if packet['cmd'] == 'out':
            # Call os.write manually. In Python2.6, sys.stdout.write doesn't use UTF-8.
            os.write(sys.stdout.fileno(), packet['data'].encode('utf-8'))

        elif packet['cmd'] == 'suspend':
            # Suspend client process to background.
            if hasattr(signal, 'SIGTSTP'):
                os.kill(os.getpid(), signal.SIGTSTP)

        elif packet['cmd'] == 'mode':
            # Set terminal to raw/cooked.
            action = packet['data']

            if action == 'raw':
                cm = raw_mode(sys.stdin.fileno())
                cm.__enter__()
                self._mode_context_managers.append(cm)

            elif action == 'cooked':
                cm = cooked_mode(sys.stdin.fileno())
                cm.__enter__()
                self._mode_context_managers.append(cm)

            elif action == 'restore' and self._mode_context_managers:
                cm = self._mode_context_managers.pop()
                cm.__exit__() 
Example #21
Source File: ptrace.py    From ptracer with Apache License 2.0 5 votes vote down vote up
def is_stop_signal(signum):
    return signum in (signal.SIGSTOP, signal.SIGTSTP,
                      signal.SIGTTIN, signal.SIGTTOU) 
Example #22
Source File: test_worker.py    From ndkale with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def testCleanupWorkerSuspend(self):
        """Test cleanup worker."""
        mock_consumer = self._create_patch('kale.consumer.Consumer')
        release_batch = self._create_patch('kale.worker.Worker._release_batch')
        sys_exit = self._create_patch('sys.exit')
        worker_inst = worker.Worker()
        mock_consumer.assert_called_once_with()
        release_batch.return_value = (0, 0)
        worker_inst._cleanup_worker(signal.SIGTSTP, None)
        release_batch.assert_called_once_with()
        assert not sys_exit.called, 'System should not have exited.' 
Example #23
Source File: screen.py    From asciimatics with Apache License 2.0 5 votes vote down vote up
def _catch_interrupt(signal_no, frame):
            """
            SIGINT handler.  We ignore the signal and frame info passed in.
            """
            # Stop pep-8 shouting at me for unused params I can't control.
            del frame

            # The OS already caught the ctrl-c, so inject it now for the next
            # input.
            if signal_no == signal.SIGINT:
                curses.ungetch(3)
            elif signal_no == signal.SIGTSTP:
                curses.ungetch(26) 
Example #24
Source File: worker.py    From ndkale with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _on_sigtstp(self, num_completed, num_incomplete):
        """Callback function when SIGTSTP is triggered.

        :param int num_completed: the number of tasks completed in this batch.
        :param int num_incomplete: the number of tasks incomplete in the batch.
        """
        logger.info(
            ('Taskworker process suspended. Completed tasks: %d;'
             ' Incomplete: %d') % (
                num_completed, num_incomplete)) 
Example #25
Source File: main.py    From polysh with GNU General Public License v2.0 4 votes vote down vote up
def loop(interactive: bool) -> None:
    histfile = os.path.expanduser("~/.polysh_history")
    init_history(histfile)
    next_signal = None
    last_status = None
    while True:
        try:
            if next_signal:
                current_signal = next_signal
                next_signal = None
                sig2chr = {signal.SIGINT: 'C', signal.SIGTSTP: 'Z'}
                ctrl = sig2chr[current_signal]
                remote_dispatcher.log('> ^{}\n'.format(ctrl).encode())
                control_commands.do_send_ctrl(ctrl)
                console_output(b'')
                stdin.the_stdin_thread.prepend_text = None
            while dispatchers.count_awaited_processes()[0] and \
                    remote_dispatcher.main_loop_iteration(timeout=0.2):
                pass
            # Now it's quiet
            for r in dispatchers.all_instances():
                r.print_unfinished_line()
            current_status = dispatchers.count_awaited_processes()
            if current_status != last_status:
                console_output(b'')
            if remote_dispatcher.options.interactive:
                stdin.the_stdin_thread.want_raw_input()
            last_status = current_status
            if dispatchers.all_terminated():
                # Clear the prompt
                console_output(b'')
                raise asyncore.ExitNow(remote_dispatcher.options.exit_code)
            if not next_signal:
                # possible race here with the signal handler
                remote_dispatcher.main_loop_iteration()
        except KeyboardInterrupt:
            if interactive:
                next_signal = signal.SIGINT
            else:
                kill_all()
                os.kill(0, signal.SIGINT)
        except asyncore.ExitNow as e:
            console_output(b'')
            save_history(histfile)
            sys.exit(e.args[0])