Python signal.SIGTERM Examples

The following are 30 code examples of signal.SIGTERM(). 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: background.py    From wechat-alfred-workflow with MIT License 7 votes vote down vote up
def kill(name, sig=signal.SIGTERM):
    """Send a signal to job ``name`` via :func:`os.kill`.

    .. versionadded:: 1.29

    Args:
        name (str): Name of the job
        sig (int, optional): Signal to send (default: SIGTERM)

    Returns:
        bool: `False` if job isn't running, `True` if signal was sent.
    """
    pid = _job_pid(name)
    if pid is None:
        return False

    os.kill(pid, sig)
    return True 
Example #2
Source File: streamserver.py    From pulseaudio-dlna with GNU General Public License v3.0 7 votes vote down vote up
def run(self):
        self.allow_reuse_address = True
        self.daemon_threads = True
        try:
            SocketServer.TCPServer.__init__(
                self, (self.ip or '', self.port), StreamRequestHandler)
        except socket.error:
            logger.critical(
                'The streaming server could not bind to your specified port '
                '({port}). Perhaps this is already in use? The application '
                'cannot work properly!'.format(port=self.port))
            sys.exit(1)

        signal.signal(signal.SIGTERM, self.shutdown)
        if self.proc_title:
            setproctitle.setproctitle(self.proc_title)
        self.serve_forever() 
Example #3
Source File: gen.py    From multibootusb with GNU General Public License v2.0 7 votes vote down vote up
def process_exist(process_name):
    """
    Detect if process exist/ running and kill it.
    :param process_name: process name to check
    :return: True if processis killed else False
    """
    if platform.system() == 'Windows':
        import signal
        import wmi
        c = wmi.WMI()
        for process in c.Win32_Process():
            if process_name in process.Name:
                log(process_name + ' exist...')
                log(str(process.ProcessId) + ' ' + str(process.Name))
                log("Having Windows explorer won't allow dd.exe to write ISO image properly."
                      "\nKilling the process..")
                try:
                    os.kill(process.ProcessId, signal.SIGTERM)
                    return True
                except:
                    log('Unable to kill process ' + str(process.ProcessId))

    return False 
Example #4
Source File: background.py    From gist-alfred with MIT License 7 votes vote down vote up
def kill(name, sig=signal.SIGTERM):
    """Send a signal to job ``name`` via :func:`os.kill`.

    .. versionadded:: 1.29

    Args:
        name (str): Name of the job
        sig (int, optional): Signal to send (default: SIGTERM)

    Returns:
        bool: `False` if job isn't running, `True` if signal was sent.
    """
    pid = _job_pid(name)
    if pid is None:
        return False

    os.kill(pid, sig)
    return True 
Example #5
Source File: test_states.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_SIGTERM(self):
        'SIGTERM should shut down the server whether daemonized or not.'
        self._require_signal_and_kill('SIGTERM')

        # Spawn a normal, undaemonized process.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'))
        p.write_conf(
            extra='test_case_name: "test_SIGTERM"')
        p.start(imports='cherrypy.test._test_states_demo')
        # Send a SIGTERM
        os.kill(p.get_pid(), signal.SIGTERM)
        # This might hang if things aren't working right, but meh.
        p.join()

        if os.name in ['posix']:
            # Spawn a daemonized process and test again.
            p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'),
                                 wait=True, daemonize=True)
            p.write_conf(
                extra='test_case_name: "test_SIGTERM_2"')
            p.start(imports='cherrypy.test._test_states_demo')
            # Send a SIGTERM
            os.kill(p.get_pid(), signal.SIGTERM)
            # This might hang if things aren't working right, but meh.
            p.join() 
Example #6
Source File: test_fmwk.py    From molotov with Apache License 2.0 6 votes vote down vote up
def test_shutdown_exception(self):
        @teardown()
        def _worker_teardown(num):
            raise Exception("bleh")

        @global_teardown()
        def _teardown():
            raise Exception("bleh")

        @scenario(weight=100)
        async def test_two(session):
            os.kill(os.getpid(), signal.SIGTERM)

        args = self.get_args()
        results = Runner(args)()
        self.assertEqual(results["OK"], 1) 
Example #7
Source File: test_fmwk.py    From molotov with Apache License 2.0 6 votes vote down vote up
def test_shutdown(self):
        res = []

        @teardown()
        def _worker_teardown(num):
            res.append("BYE WORKER")

        @global_teardown()
        def _teardown():
            res.append("BYE")

        @scenario(weight=100)
        async def test_two(session):
            os.kill(os.getpid(), signal.SIGTERM)

        args = self.get_args()
        results = Runner(args)()

        self.assertEqual(results["OK"], 1)
        self.assertEqual(results["FAILED"], 0)
        self.assertEqual(res, ["BYE WORKER", "BYE"]) 
Example #8
Source File: linux_pty.py    From TerminalView with MIT License 6 votes vote down vote up
def stop(self):
        """
        Stop the shell
        """
        if self.is_running():
            try:
                os.kill(self._shell_pid, signal.SIGTERM)
            except OSError:
                pass

        start = time.time()
        while self.is_running() and (time.time() < (start + 0.2)):
            time.sleep(0.05)

        if self.is_running():
            utils.ConsoleLogger.log("Failed to stop shell process")
        else:
            utils.ConsoleLogger.log("Shell process stopped") 
Example #9
Source File: verifier.py    From ffw with GNU General Public License v3.0 6 votes vote down vote up
def stopChild(self):
        logging.debug("Terminate child...")
        if self.p is not None:
            self.p.terminate()

        logging.debug("Kill server: " + str(self.serverPid))

        if self.serverPid is not None:
            try:
                os.kill(self.serverPid, signal.SIGTERM)
                os.kill(self.serverPid, signal.SIGKILL)
            except Exception as e:
                logging.error("Kill exception, but child should be alive: " + str(e))

        self.p = None
        self.serverPid = None

    ######################## 
Example #10
Source File: pods.py    From python-podman with Apache License 2.0 6 votes vote down vote up
def kill(self, signal_=signal.SIGTERM, wait=25):
        """Send signal to all containers in pod.

        default signal is signal.SIGTERM.
        wait n of seconds, 0 waits forever.
        """
        with self._client() as podman:
            podman.KillPod(self._ident, signal_)
            timeout = time.time() + wait
            while True:
                # pylint: disable=maybe-no-member
                self._refresh(podman)
                running = FoldedString(self.status)
                if running != 'running':
                    break

                if wait and timeout < time.time():
                    raise TimeoutError()

                time.sleep(0.5)
        return self 
Example #11
Source File: mqtt2sql.py    From mqtt2sql with GNU General Public License v3.0 6 votes vote down vote up
def exitus(self, status=0, message="end"):
        """
        Called when the program should be exit

        @param status:
            the exit status program returns to callert
        @param message:
            the message logged before exit
        """
        # pylint: disable=global-statement
        global SCRIPTNAME
        global SCRIPTPID
        global VER
        # pylint: enable=global-statement
        if message is not None:
            log(1, message)
        log(0, '{}[{}] v{} end'.format(SCRIPTNAME, SCRIPTPID, VER))
        if status in (signal.SIGINT, signal.SIGTERM):
            status = 0
        sys.exit(status) 
Example #12
Source File: Radiumkeylogger.py    From Radium with Apache License 2.0 6 votes vote down vote up
def deleteoldstub():
    checkfilename = 'AdobePush.exe'     #The exe in the startup will be saved by the name of AdobePush. When the exe will be updated the old exe will be deleted.
    checkdir = 'C://Users//' + currentuser + '//AppData//Roaming//Microsoft//Windows//Start Menu//Programs//Startup//'
    dircontent = os.listdir(checkdir)

    try:
        try:
            pids = getpid('AdobePush.exe')
            for id in pids:
                os.kill(int(id), signal.SIGTERM)
        except Exception as e:
            print e

        if checkfilename in dircontent:
            os.remove(checkdir + checkfilename)
    except Exception as e:
        print e

#Function to copy the exe to startup 
Example #13
Source File: containers.py    From python-podman with Apache License 2.0 6 votes vote down vote up
def kill(self, sig=signal.SIGTERM, wait=25):
        """Send signal to container.

        default signal is signal.SIGTERM.
        wait n of seconds, 0 waits forever.
        """
        with self._client() as podman:
            podman.KillContainer(self._id, sig)
            timeout = time.time() + wait
            while True:
                self._refresh(podman)
                if self.status != 'running':  # pylint: disable=no-member
                    return self

                if wait and timeout < time.time():
                    raise TimeoutError()

                time.sleep(0.5) 
Example #14
Source File: test_result.py    From tox with MIT License 6 votes vote down vote up
def test_invocation_error(exit_code, os_name, mocker, monkeypatch):
    monkeypatch.setattr(os, "name", value=os_name)
    mocker.spy(tox.exception, "exit_code_str")
    result = str(tox.exception.InvocationError("<command>", exit_code=exit_code))
    # check that mocker works, because it will be our only test in
    # test_z_cmdline.py::test_exit_code needs the mocker.spy above
    assert tox.exception.exit_code_str.call_count == 1
    call_args = tox.exception.exit_code_str.call_args
    assert call_args == mocker.call("InvocationError", "<command>", exit_code)
    if exit_code is None:
        assert "(exited with code" not in result
    elif exit_code == -15:
        assert "(exited with code -15 (SIGTERM))" in result
    else:
        assert "(exited with code {})".format(exit_code) in result
        note = "Note: this might indicate a fatal error signal"
        if (os_name == "posix") and (exit_code == 128 + signal.SIGTERM):
            assert note in result
            assert "({} - 128 = {}: SIGTERM)".format(exit_code, signal.SIGTERM) in result
        else:
            assert note not in result 
Example #15
Source File: model_server.py    From sagemaker-xgboost-container with Apache License 2.0 5 votes vote down vote up
def _add_sigterm_handler(mms_process):
    def _terminate(signo, frame):
        try:
            os.kill(mms_process.pid, signal.SIGTERM)
        except OSError:
            pass

    signal.signal(signal.SIGTERM, _terminate) 
Example #16
Source File: git_multimail_upstream.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def send(self, lines, to_addrs):
        try:
            p = subprocess.Popen(self.command, stdin=subprocess.PIPE)
        except OSError:
            self.environment.get_logger().error(
                "*** Cannot execute command: %s\n" % " ".join(self.command)
                + "*** %s\n" % sys.exc_info()[1]
                + '*** Try setting multimailhook.mailer to "smtp"\n'
                + "*** to send emails without using the sendmail command.\n"
            )
            sys.exit(1)
        try:
            lines = (str_to_bytes(line) for line in lines)
            p.stdin.writelines(lines)
        except Exception:
            self.environment.get_logger().error(
                "*** Error while generating commit email\n"
                "***  - mail sending aborted.\n"
            )
            if hasattr(p, "terminate"):
                # subprocess.terminate() is not available in Python 2.4
                p.terminate()
            else:
                import signal

                os.kill(p.pid, signal.SIGTERM)
            raise
        else:
            p.stdin.close()
            retcode = p.wait()
            if retcode:
                raise CommandError(self.command, retcode) 
Example #17
Source File: support.py    From molotov with Apache License 2.0 5 votes vote down vote up
def coserver(port=8888):
    if _CO["clients"] == 0:
        _CO["server"] = run_server(port)

    _CO["clients"] += 1
    try:
        yield
    finally:
        _CO["clients"] -= 1
        if _CO["clients"] == 0:
            os.kill(_CO["server"].pid, signal.SIGTERM)
            _CO["server"].join(timeout=1.0)
            _CO["server"].terminate()
            _CO["server"] = None 
Example #18
Source File: auto_closing_service.py    From tomodachi with MIT License 5 votes vote down vote up
def _started_service(self) -> None:
        self.started = True
        await asyncio.sleep(0.1)
        os.kill(os.getpid(), signal.SIGTERM) 
Example #19
Source File: run_example_service.py    From tomodachi with MIT License 5 votes vote down vote up
def _started_service(self) -> None:
        self.log('_started_service() function called')
        self.started = True
        await asyncio.sleep(0.1)
        os.kill(os.getpid(), signal.SIGTERM) 
Example #20
Source File: test_gipc.py    From gipc with MIT License 5 votes vote down vote up
def test_orphaned_signal_watcher(self):
        # Install libev-based signal watcher.
        try:
            s = gevent.signal(signal.SIGTERM, signals_test_sigterm_handler)
        except AttributeError:
            # This function got renamed in gevent 1.5
            s = gevent.signal_handler(signal.SIGTERM, signals_test_sigterm_handler)
        # Normal behavior: signal handlers become inherited by children.
        # Bogus behavior of libev-based signal watchers in child process:
        # They should not be active anymore when 'orphaned' (when their
        # corresponding event loop has been destroyed). What happens, however:
        # The old handler stays active and registering a new handler does not
        # 'overwrite' the old one -- both are active.
        # Since this test is about testing the behavior of 'orphaned' libev
        # signal watchers, the signal must be transmitted *after* event loop
        # recreation, so wait here for the child process to go through
        # the hub & event loop destruction (and recreation) process before
        # sending the signal. Waiting is realized with sync through pipe.
        # Without cleanup code in gipc, the inherited but orphaned libev signal
        # watcher would be active in the fresh event loop and trigger the
        # handler. This is a problem. With cleanup code, this handler must
        # never be called. Child exitcode 20 means that the inherited handler
        # has been called, -15 (-signal.SIGTERM) means that the child was
        # actually killed by SIGTERM within a certain short time interval.
        # Returncode 0 would mean that the child finished normally after that
        # short time interval.
        with pipe() as (r, w):
            p = start_process(signals_test_child_a, (w,))
            assert r.get() == p.pid
            os.kill(p.pid, signal.SIGTERM)
            p.join()
            if not WINDOWS:
                assert p.exitcode == -signal.SIGTERM
            else:
                assert p.exitcode == signal.SIGTERM
        s.cancel() 
Example #21
Source File: test_gipc.py    From gipc with MIT License 5 votes vote down vote up
def test_terminate(self):
        p = start_process(gevent.sleep, args=(1,))
        # Test __repr__ and __str__
        p.__repr__()
        p.terminate()
        p.join()
        p.__repr__()
        assert p.exitcode == -signal.SIGTERM
        _call_close_method_if_exists(p) 
Example #22
Source File: test_data_utils.py    From sagemaker-xgboost-container with Apache License 2.0 5 votes vote down vote up
def _check_piped_dmatrix(self, file_path, pipe_path, pipe_dir, reader, num_col, num_row, *args):
        python_exe = sys.executable
        pipe_cmd = '{}/sagemaker_pipe.py train {} {}'.format(self.utils_path, file_path, pipe_dir)

        proc = subprocess.Popen([python_exe] + pipe_cmd.split(" "))

        try:
            time.sleep(1)
            self._check_dmatrix(reader, pipe_path, num_col, num_row, *args)
        finally:
            os.kill(proc.pid, signal.SIGTERM)
            shutil.rmtree(pipe_dir) 
Example #23
Source File: twisted_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def save_signal_handlers():
    saved = {}
    for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGCHLD]:
        saved[sig] = signal.getsignal(sig)
    if "twisted" in repr(saved):
        if not issubclass(IOLoop.configured_class(), TwistedIOLoop):
            # when the global ioloop is twisted, we expect the signal
            # handlers to be installed.  Otherwise, it means we're not
            # cleaning up after twisted properly.
            raise Exception("twisted signal handlers already installed")
    return saved 
Example #24
Source File: crashsignal.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def interrupt_really_forcefully(self, signum, _frame):
        """Interrupt with even more force on the third SIGINT/SIGTERM request.

        This doesn't run *any* Qt cleanup and simply exits via Python.
        It will most likely lead to a segfault.
        """
        print("WHY ARE YOU DOING THIS TO ME? :(")
        sys.exit(128 + signum) 
Example #25
Source File: logging_service.py    From tomodachi with MIT License 5 votes vote down vote up
def _started_service(self) -> None:
        self.log('_started_service', level=logging.INFO)
        await asyncio.sleep(0.1)
        os.kill(os.getpid(), signal.SIGTERM) 
Example #26
Source File: crashsignal.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def interrupt_forcefully(self, signum, _frame):
        """Interrupt forcefully on the second SIGINT/SIGTERM request.

        This skips our shutdown routine and calls QApplication:exit instead.
        It then remaps the signals to call self.interrupt_really_forcefully the
        next time.
        """
        signal.signal(signal.SIGINT, self.interrupt_really_forcefully)
        signal.signal(signal.SIGTERM, self.interrupt_really_forcefully)
        # Signals can arrive anywhere, so we do this in the main thread
        self._log_later("Forceful quit requested, goodbye cruel world!",
                        "Do the same again to quit with even more force.")
        QTimer.singleShot(0, functools.partial(self._app.exit, 128 + signum)) 
Example #27
Source File: crashsignal.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def interrupt(self, signum, _frame):
        """Handler for signals to gracefully shutdown (SIGINT/SIGTERM).

        This calls shutdown and remaps the signal to call
        interrupt_forcefully the next time.
        """
        signal.signal(signal.SIGINT, self.interrupt_forcefully)
        signal.signal(signal.SIGTERM, self.interrupt_forcefully)
        # Signals can arrive anywhere, so we do this in the main thread
        self._log_later("SIGINT/SIGTERM received, shutting down!",
                        "Do the same again to forcefully quit.")
        QTimer.singleShot(0, functools.partial(
            self._quitter.shutdown, 128 + signum)) 
Example #28
Source File: crashsignal.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def activate(self):
        """Set up signal handlers.

        On Windows this uses a QTimer to periodically hand control over to
        Python so it can handle signals.

        On Unix, it uses a QSocketNotifier with os.set_wakeup_fd to get
        notified.
        """
        self._orig_handlers[signal.SIGINT] = signal.signal(
            signal.SIGINT, self.interrupt)
        self._orig_handlers[signal.SIGTERM] = signal.signal(
            signal.SIGTERM, self.interrupt)

        if utils.is_posix and hasattr(signal, 'set_wakeup_fd'):
            # pylint: disable=import-error,no-member,useless-suppression
            import fcntl
            read_fd, write_fd = os.pipe()
            for fd in [read_fd, write_fd]:
                flags = fcntl.fcntl(fd, fcntl.F_GETFL)
                fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
            self._notifier = QSocketNotifier(typing.cast(sip.voidptr, read_fd),
                                             QSocketNotifier.Read,
                                             self)
            self._notifier.activated.connect(  # type: ignore[attr-defined]
                self.handle_signal_wakeup)
            self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd)
            # pylint: enable=import-error,no-member,useless-suppression
        else:
            self._timer.start(1000)
            self._timer.timeout.connect(lambda: None)
        self._activated = True 
Example #29
Source File: process_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_sigchild_signal(self):
        skip_if_twisted()
        Subprocess.initialize(io_loop=self.io_loop)
        self.addCleanup(Subprocess.uninitialize)
        subproc = Subprocess([sys.executable, '-c',
                              'import time; time.sleep(30)'],
                             io_loop=self.io_loop)
        subproc.set_exit_callback(self.stop)
        os.kill(subproc.pid, signal.SIGTERM)
        ret = self.wait()
        self.assertEqual(subproc.returncode, ret)
        self.assertEqual(ret, -signal.SIGTERM) 
Example #30
Source File: mqtt2sql.py    From mqtt2sql with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        signal.signal(signal.SIGINT, self._exitus)
        signal.signal(signal.SIGTERM, self._exitus)