Python signal.CTRL_BREAK_EVENT Examples

The following are 30 code examples of signal.CTRL_BREAK_EVENT(). 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 QCEngine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def terminate_process(proc: Any, timeout: int = 15) -> None:
    if proc.poll() is None:

        # Sigint (keyboard interupt)
        if sys.platform.startswith("win"):
            proc.send_signal(signal.CTRL_BREAK_EVENT)
        else:
            proc.send_signal(signal.SIGINT)

        try:
            start = time.time()
            while (proc.poll() is None) and (time.time() < (start + timeout)):
                time.sleep(0.02)

        # Flat kill
        finally:
            proc.kill() 
Example #2
Source File: _signals_windows.py    From py_daemoniker with The Unlicense 6 votes vote down vote up
def _default_handler(signum, *args):
        ''' The default signal handler. Don't register with built-in
        signal.signal! This needs to be used on the subprocess await
        death workaround.
        '''
        # All valid cpython windows signals
        sigs = {
            signal.SIGABRT: SIGABRT,
            # signal.SIGFPE: 'fpe', # Don't catch this
            # signal.SIGSEGV: 'segv', # Don't catch this
            # signal.SIGILL: 'illegal', # Don't catch this
            signal.SIGINT: SIGINT,
            signal.SIGTERM: SIGTERM,
            # Note that signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT are
            # converted to SIGINT in _await_signal
        }
        
        try:
            exc = sigs[signum]
        except KeyError:
            exc = DaemonikerSignal
            
        _sketch_raise_in_main(exc) 
Example #3
Source File: test_process.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_kill_terminate(self):
        # subprocess.Popen()'s terminate(), kill() and send_signal() do
        # not raise exception after the process is gone. psutil.Popen
        # diverges from that.
        cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"]
        with psutil.Popen(cmd, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE) as proc:
            proc.terminate()
            proc.wait()
            self.assertRaises(psutil.NoSuchProcess, proc.terminate)
            self.assertRaises(psutil.NoSuchProcess, proc.kill)
            self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                              signal.SIGTERM)
            if WINDOWS and sys.version_info >= (2, 7):
                self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                                  signal.CTRL_C_EVENT)
                self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                                  signal.CTRL_BREAK_EVENT) 
Example #4
Source File: test_process.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_kill_terminate(self):
        # subprocess.Popen()'s terminate(), kill() and send_signal() do
        # not raise exception after the process is gone. psutil.Popen
        # diverges from that.
        cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"]
        with psutil.Popen(cmd, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE) as proc:
            proc.terminate()
            proc.wait()
            self.assertRaises(psutil.NoSuchProcess, proc.terminate)
            self.assertRaises(psutil.NoSuchProcess, proc.kill)
            self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                              signal.SIGTERM)
            if WINDOWS and sys.version_info >= (2, 7):
                self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                                  signal.CTRL_C_EVENT)
                self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                                  signal.CTRL_BREAK_EVENT) 
Example #5
Source File: subprocess42.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def terminate(self):
    """Tries to do something saner on Windows that the stdlib.

    Windows:
      self.detached/CREATE_NEW_PROCESS_GROUP determines what can be used:
      - If set, only SIGBREAK can be sent and it is sent to a single process.
      - If not set, in theory only SIGINT can be used and *all processes* in
         the processgroup receive it. In practice, we just kill the process.
      See http://msdn.microsoft.com/library/windows/desktop/ms683155.aspx
      The default on Windows is to call TerminateProcess() always, which is not
      useful.

    On Posix, always send SIGTERM.
    """
    try:
      if sys.platform == 'win32' and self.detached:
        return self.send_signal(signal.CTRL_BREAK_EVENT)
      super(Popen, self).terminate()
    except OSError:
      # The function will throw if the process terminated in-between. Swallow
      # this.
      pass 
Example #6
Source File: popen_spawn.py    From pipenv with MIT License 6 votes vote down vote up
def kill(self, sig):
        '''Sends a Unix signal to the subprocess.

        Use constants from the :mod:`signal` module to specify which signal.
        '''
        if sys.platform == 'win32':
            if sig in [signal.SIGINT, signal.CTRL_C_EVENT]:
                sig = signal.CTRL_C_EVENT
            elif sig in [signal.SIGBREAK, signal.CTRL_BREAK_EVENT]:
                sig = signal.CTRL_BREAK_EVENT
            else:
                sig = signal.SIGTERM

        os.kill(self.proc.pid, sig) 
Example #7
Source File: test_process.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_kill_terminate(self):
        # subprocess.Popen()'s terminate(), kill() and send_signal() do
        # not raise exception after the process is gone. psutil.Popen
        # diverges from that.
        cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"]
        with psutil.Popen(cmd, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE) as proc:
            proc.terminate()
            proc.wait()
            self.assertRaises(psutil.NoSuchProcess, proc.terminate)
            self.assertRaises(psutil.NoSuchProcess, proc.kill)
            self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                              signal.SIGTERM)
            if WINDOWS and sys.version_info >= (2, 7):
                self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                                  signal.CTRL_C_EVENT)
                self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                                  signal.CTRL_BREAK_EVENT) 
Example #8
Source File: ray_process_reaper.py    From ray with Apache License 2.0 6 votes vote down vote up
def reap_process_group(*args):
    def sigterm_handler(*args):
        # Give a one-second grace period for other processes to clean up.
        time.sleep(SIGTERM_GRACE_PERIOD_SECONDS)
        # SIGKILL the pgroup (including ourselves) as a last-resort.
        if sys.platform == "win32":
            atexit.unregister(sigterm_handler)
            os.kill(0, signal.CTRL_BREAK_EVENT)
        else:
            os.killpg(0, signal.SIGKILL)

    # Set a SIGTERM handler to handle SIGTERMing ourselves with the group.
    if sys.platform == "win32":
        atexit.register(sigterm_handler)
    else:
        signal.signal(signal.SIGTERM, sigterm_handler)

    # Our parent must have died, SIGTERM the group (including ourselves).
    if sys.platform == "win32":
        os.kill(0, signal.CTRL_C_EVENT)
    else:
        os.killpg(0, signal.SIGTERM) 
Example #9
Source File: soapy_power.py    From qspectrumanalyzer with GNU General Public License v3.0 6 votes vote down vote up
def process_stop(self):
        """Stop soapy_power process"""
        with self._shutdown_lock:
            if self.process:
                if self.process.poll() is None:
                    try:
                        if sys.platform == 'win32':
                            self.process.send_signal(signal.CTRL_BREAK_EVENT)
                        else:
                            self.process.terminate()
                    except ProcessLookupError:
                        pass
                self.process.wait()
                self.process = None

                # Close pipe used for communication with soapy_power process
                self.pipe_read.close()

                self.pipe_read = None
                self.pipe_read_fd = None
                self.pipe_write_fd = None
                self.pipe_write_handle = None 
Example #10
Source File: test_win.py    From aiorun with Apache License 2.0 5 votes vote down vote up
def test_sig():
    """Basic SIGTERM"""
    proc = sp.Popen(
        [sys.executable, "tests/fake_main.py"],
        stdout=sp.PIPE,
        stderr=sp.STDOUT,
        creationflags=sp.CREATE_NEW_PROCESS_GROUP,
    )
    time.sleep(0.5)
    # proc.send_signal(signal.CTRL_BREAK_EVENT)
    # os.kill(proc.pid, signal.CTRL_C_EVENT)
    os.kill(proc.pid, signal.CTRL_BREAK_EVENT)
    print("Send signal")
    proc.wait(timeout=5)
    stdout = proc.stdout.read().decode()
    print(stdout)
    assert proc.returncode == 0

    expected = [
        "Entering run()",
        "Entering shutdown phase",
        "Cancelling pending tasks",
        "Closing the loop",
        "Bye!",
    ]

    for phrase in expected:
        assert phrase in stdout 
Example #11
Source File: utils.py    From cmd2 with MIT License 5 votes vote down vote up
def send_sigint(self) -> None:
        """Send a SIGINT to the process similar to if <Ctrl>+C were pressed"""
        import signal
        if sys.platform.startswith('win'):
            # cmd2 started the Windows process in a new process group. Therefore
            # a CTRL_C_EVENT can't be sent to it. Send a CTRL_BREAK_EVENT instead.
            self._proc.send_signal(signal.CTRL_BREAK_EVENT)
        else:
            # Since cmd2 uses shell=True in its Popen calls, we need to send the SIGINT to
            # the whole process group to make sure it propagates further than the shell
            try:
                group_id = os.getpgid(self._proc.pid)
                os.killpg(group_id, signal.SIGINT)
            except ProcessLookupError:
                return 
Example #12
Source File: test_pytest_cov.py    From pytest-cov with MIT License 5 votes vote down vote up
def test_cleanup_on_sigterm_sig_break(testdir, setup):
    # worth a read: https://stefan.sofa-rockers.org/2013/08/15/handling-sub-process-hierarchies-python-linux-os-x/
    script = testdir.makepyfile('''
import os, signal, subprocess, sys, time

def test_run():
    proc = subprocess.Popen(
        [sys.executable, __file__],
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
        creationflags=subprocess.CREATE_NEW_PROCESS_GROUP, shell=True
    )
    time.sleep(1)
    proc.send_signal(signal.CTRL_BREAK_EVENT)
    stdout, stderr = proc.communicate()
    assert not stderr
    assert stdout in [b"^C", b"", b"captured IOError(4, 'Interrupted function call')\\n"]

if __name__ == "__main__":
    from pytest_cov.embed import cleanup_on_signal, cleanup
    ''' + setup[0] + '''

    try:
        time.sleep(10)
    except BaseException as exc:
        print("captured %r" % exc)
''')

    result = testdir.runpytest('-vv',
                               '--cov=%s' % script.dirpath(),
                               '--cov-report=term-missing',
                               script)

    result.stdout.fnmatch_lines([
        '*- coverage: platform *, python * -*',
        'test_cleanup_on_sigterm* %s' % setup[1],
        '*1 passed*'
    ])
    assert result.ret == 0 
Example #13
Source File: subprocess.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def send_signal(self, sig):
            """Send a signal to the process
            """
            if sig == signal.SIGTERM:
                self.terminate()
            elif sig == signal.CTRL_C_EVENT:
                os.kill(self.pid, signal.CTRL_C_EVENT)
            elif sig == signal.CTRL_BREAK_EVENT:
                os.kill(self.pid, signal.CTRL_BREAK_EVENT)
            else:
                raise ValueError("Unsupported signal: {}".format(sig)) 
Example #14
Source File: win_console_handler.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _ctrl_handler(sig):
    """Handle a sig event and return 0 to terminate the process"""
    if sig == signal.CTRL_C_EVENT:
        pass
    elif sig == signal.CTRL_BREAK_EVENT:
        pass
    else:
        print("UNKNOWN EVENT")
    return 0 
Example #15
Source File: test_os.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_CTRL_BREAK_EVENT(self):
        self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT") 
Example #16
Source File: test_windows.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_ctrl_signals(self):
        p = psutil.Process(get_test_subprocess().pid)
        p.send_signal(signal.CTRL_C_EVENT)
        p.send_signal(signal.CTRL_BREAK_EVENT)
        p.kill()
        p.wait()
        self.assertRaises(psutil.NoSuchProcess,
                          p.send_signal, signal.CTRL_C_EVENT)
        self.assertRaises(psutil.NoSuchProcess,
                          p.send_signal, signal.CTRL_BREAK_EVENT) 
Example #17
Source File: subprocess.py    From RevitBatchProcessor with GNU General Public License v3.0 5 votes vote down vote up
def send_signal(self, sig):
            """Send a signal to the process
            """
            if sig == signal.SIGTERM:
                self.terminate()
            elif sig == signal.CTRL_C_EVENT:
                os.kill(self.pid, signal.CTRL_C_EVENT)
            elif sig == signal.CTRL_BREAK_EVENT:
                os.kill(self.pid, signal.CTRL_BREAK_EVENT)
            else:
                raise ValueError("Unsupported signal: {}".format(sig)) 
Example #18
Source File: subprocess.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def send_signal(self, sig):
            """Send a signal to the process
            """
            if sig == signal.SIGTERM:
                self.terminate()
            elif sig == signal.CTRL_C_EVENT:
                os.kill(self.pid, signal.CTRL_C_EVENT)
            elif sig == signal.CTRL_BREAK_EVENT:
                os.kill(self.pid, signal.CTRL_BREAK_EVENT)
            else:
                raise ValueError("Unsupported signal: {}".format(sig)) 
Example #19
Source File: subprocess.py    From unity-python with MIT License 5 votes vote down vote up
def send_signal(self, sig):
            """Send a signal to the process
            """
            if sig == signal.SIGTERM:
                self.terminate()
            elif sig == signal.CTRL_C_EVENT:
                os.kill(self.pid, signal.CTRL_C_EVENT)
            elif sig == signal.CTRL_BREAK_EVENT:
                os.kill(self.pid, signal.CTRL_BREAK_EVENT)
            else:
                raise ValueError("Unsupported signal: {}".format(sig)) 
Example #20
Source File: subprocess.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def send_signal(self, sig):
            """Send a signal to the process
            """
            if sig == signal.SIGTERM:
                self.terminate()
            elif sig == signal.CTRL_C_EVENT:
                os.kill(self.pid, signal.CTRL_C_EVENT)
            elif sig == signal.CTRL_BREAK_EVENT:
                os.kill(self.pid, signal.CTRL_BREAK_EVENT)
            else:
                raise ValueError("Unsupported signal: {}".format(sig)) 
Example #21
Source File: win_console_handler.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _ctrl_handler(sig):
    """Handle a sig event and return 0 to terminate the process"""
    if sig == signal.CTRL_C_EVENT:
        pass
    elif sig == signal.CTRL_BREAK_EVENT:
        pass
    else:
        print("UNKNOWN EVENT")
    return 0 
Example #22
Source File: test_os.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_CTRL_BREAK_EVENT(self):
        self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT") 
Example #23
Source File: _cpcompat_subprocess.py    From opsbro with MIT License 5 votes vote down vote up
def send_signal(self, sig):
            """Send a signal to the process
            """
            if sig == signal.SIGTERM:
                self.terminate()
            elif sig == signal.CTRL_C_EVENT:
                os.kill(self.pid, signal.CTRL_C_EVENT)
            elif sig == signal.CTRL_BREAK_EVENT:
                os.kill(self.pid, signal.CTRL_BREAK_EVENT)
            else:
                raise ValueError("Unsupported signal: {}".format(sig)) 
Example #24
Source File: subprocess.py    From service-manager with Apache License 2.0 5 votes vote down vote up
def send_signal(self, sig):
            """Send a signal to the process
            """
            if sig == signal.SIGTERM:
                self.terminate()
            elif sig == signal.CTRL_C_EVENT:
                os.kill(self.pid, signal.CTRL_C_EVENT)
            elif sig == signal.CTRL_BREAK_EVENT:
                os.kill(self.pid, signal.CTRL_BREAK_EVENT)
            else:
                raise ValueError("Unsupported signal: {}".format(sig)) 
Example #25
Source File: services.py    From ray with Apache License 2.0 5 votes vote down vote up
def terminate(self):
            if isinstance(self.stdin, io.IOBase):
                self.stdin.close()
            if self._use_signals:
                self.send_signal(signal.CTRL_BREAK_EVENT)
            else:
                super(ConsolePopen, self).terminate() 
Example #26
Source File: command_utils.py    From nni with MIT License 5 votes vote down vote up
def kill_command(pid):
    """kill command"""
    if sys.platform == 'win32':
        process = psutil.Process(pid=pid)
        process.send_signal(signal.CTRL_BREAK_EVENT)
    else:
        cmds = ['kill', str(pid)]
        call(cmds) 
Example #27
Source File: test_signals_windows.py    From py_daemoniker with The Unlicense 5 votes vote down vote up
def test_signal_waiting(self):
        ''' Fixture thine self.
        '''
        proc1 = ProcFixture(signal.SIGINT)
        proc2 = ProcFixture(signal.SIGTERM)
        proc3 = ProcFixture(signal.SIGABRT)
        proc4 = ProcFixture(signal.CTRL_C_EVENT)
        proc5 = ProcFixture(signal.CTRL_BREAK_EVENT)
        
        self.assertEqual(_await_signal(proc1), signal.SIGINT)
        self.assertEqual(_await_signal(proc2), signal.SIGTERM)
        self.assertEqual(_await_signal(proc3), signal.SIGABRT)
        self.assertEqual(_await_signal(proc4), signal.SIGINT)
        self.assertEqual(_await_signal(proc5), signal.SIGINT) 
Example #28
Source File: _signals_windows.py    From py_daemoniker with The Unlicense 5 votes vote down vote up
def _await_signal(process):
    ''' Waits for the process to die, and then returns the exit code for
    the process, converting CTRL_C_EVENT and CTRL_BREAK_EVENT into
    SIGINT.
    '''
    # Note that this is implemented with a busy wait
    process.wait()
    code = process.returncode
    
    if code == signal.CTRL_C_EVENT:
        code = signal.SIGINT
    elif code == signal.CTRL_BREAK_EVENT:
        code = signal.SIGINT
    
    return code 
Example #29
Source File: ipc.py    From dagster with Apache License 2.0 5 votes vote down vote up
def interrupt_ipc_subprocess(proc):
    ''' Send CTRL_BREAK on Windows, SIGINT on other platforms '''

    if sys.platform == 'win32':
        proc.send_signal(signal.CTRL_BREAK_EVENT)  # pylint: disable=no-member
    else:
        proc.send_signal(signal.SIGINT) 
Example #30
Source File: win_console_handler.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _ctrl_handler(sig):
    """Handle a sig event and return 0 to terminate the process"""
    if sig == signal.CTRL_C_EVENT:
        pass
    elif sig == signal.CTRL_BREAK_EVENT:
        pass
    else:
        print("UNKNOWN EVENT")
    return 0