Python signal.SIGTERM() Examples

The following are code examples for showing how to use signal.SIGTERM(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: alfred-yubikey-otp   Author: robertoriv   File: background.py    MIT License 6 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
Project: pyblish-win   Author: pyblish   File: test_multiprocessing.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_terminate(self):
        if self.TYPE == 'threads':
            self.skipTest('test not appropriate for {}'.format(self.TYPE))

        p = self.Process(target=self._test_terminate)
        p.daemon = True
        p.start()

        self.assertEqual(p.is_alive(), True)
        self.assertIn(p, self.active_children())
        self.assertEqual(p.exitcode, None)

        p.terminate()

        join = TimingWrapper(p.join)
        self.assertEqual(join(), None)
        self.assertTimingAlmostEqual(join.elapsed, 0.0)

        self.assertEqual(p.is_alive(), False)
        self.assertNotIn(p, self.active_children())

        p.join()

        # XXX sometimes get p.exitcode == 0 on Windows ...
        #self.assertEqual(p.exitcode, -signal.SIGTERM) 
Example 3
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: background.py    MIT License 6 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 4
Project: kvmd   Author: pikvm   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def _kill_streamer(config: Section) -> None:
    logger = get_logger(0)

    if config.streamer.process_name_prefix:
        prefix = config.streamer.process_name_prefix + ":"
        logger.info("Trying to find and kill the streamer %r ...", prefix + " <app>")

        for proc in psutil.process_iter():
            attrs = proc.as_dict(attrs=["name"])
            if attrs.get("name", "").startswith(prefix):
                try:
                    proc.send_signal(signal.SIGTERM)
                except Exception:
                    logger.exception("Can't send SIGTERM to streamer with pid=%d", proc.pid)
                time.sleep(3)
                if proc.is_running():
                    try:
                        proc.send_signal(signal.SIGKILL)
                    except Exception:
                        logger.exception("Can't send SIGKILL to streamer with pid=%d", proc.pid) 
Example 5
Project: AutoDL   Author: tanguofu   File: worker.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def init_signals(self):
        # Set up signals through the event loop API.

        self.loop.add_signal_handler(signal.SIGQUIT, self.handle_quit,
                                     signal.SIGQUIT, None)

        self.loop.add_signal_handler(signal.SIGTERM, self.handle_exit,
                                     signal.SIGTERM, None)

        self.loop.add_signal_handler(signal.SIGINT, self.handle_quit,
                                     signal.SIGINT, None)

        self.loop.add_signal_handler(signal.SIGWINCH, self.handle_winch,
                                     signal.SIGWINCH, None)

        self.loop.add_signal_handler(signal.SIGUSR1, self.handle_usr1,
                                     signal.SIGUSR1, None)

        self.loop.add_signal_handler(signal.SIGABRT, self.handle_abort,
                                     signal.SIGABRT, None)

        # Don't let SIGTERM and SIGUSR1 disturb active requests
        # by interrupting system calls
        signal.siginterrupt(signal.SIGTERM, False)
        signal.siginterrupt(signal.SIGUSR1, False) 
Example 6
Project: AutoDL   Author: tanguofu   File: reloader_helpers.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def kill_process_children_unix(pid):
    """Find and kill child process of a process (maximum two level).

    :param pid: PID of process (process ID)
    :return: Nothing
    """
    root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid)
    if not os.path.isfile(root_process_path):
        return
    with open(root_process_path) as children_list_file:
        children_list_pid = children_list_file.read().split()

    for child_pid in children_list_pid:
        children_proc_path = "/proc/%s/task/%s/children" % \
            (child_pid, child_pid)
        if not os.path.isfile(children_proc_path):
            continue
        with open(children_proc_path) as children_list_file_2:
            children_list_pid_2 = children_list_file_2.read().split()
        for _pid in children_list_pid_2:
            os.kill(int(_pid), signal.SIGTERM) 
Example 7
Project: flasky   Author: RoseOu   File: service.py    MIT License 6 votes vote down vote up
def stop(self):
        """
        Cleans up the process
        """
        if self._log:
            self._log.close()
            self._log = None
        #If its dead dont worry
        if self.process is None:
            return

        #Tell the Server to properly die in case
        try:
            if self.process:
                self.process.send_signal(signal.SIGTERM)
                self.process.wait()
        except OSError:
            # kill may not be available under windows environment
            pass 
Example 8
Project: flasky   Author: RoseOu   File: arbiter.py    MIT License 6 votes vote down vote up
def stop(self, graceful=True):
        """\
        Stop workers

        :attr graceful: boolean, If True (the default) workers will be
        killed gracefully  (ie. trying to wait for the current connection)
        """
        self.LISTENERS = []
        sig = signal.SIGTERM
        if not graceful:
            sig = signal.SIGQUIT
        limit = time.time() + self.cfg.graceful_timeout
        # instruct the workers to exit
        self.kill_workers(sig)
        # wait until the graceful timeout
        while self.WORKERS and time.time() < limit:
            time.sleep(0.1)

        self.kill_workers(signal.SIGKILL) 
Example 9
Project: core   Author: lifemapper   File: daemon.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, pidfile, log=None):
        self.pidfile = pidfile
        # Default variable to indicate that the process should continue
        self.keepRunning = True 
        # Register signals
        if log is not None:
            self.log = log
        else:
            if os.path.exists(pidfile):
                with open(pidfile) as in_pid:
                    pid = in_pid.read().strip()
            else:
                pid = 'unknown'
            self.log = DaemonLogger(pid)
        
        signal.signal(signal.SIGTERM, self._receiveSignal) # Stop signal
        signal.signal(signal.SIGUSR1, self._receiveSignal) # Update signal

    # ..........................................................................

    # ============================
    # = Daemon related functions =
    # ============================
    # ............................. 
Example 10
Project: core   Author: lifemapper   File: daemon.py    GNU General Public License v3.0 6 votes vote down vote up
def _receiveSignal(self, sig_num, stack):
        """Handler used to receive signals

        Args:
            sig_num (int): The signal received
            stack: The stack at the time of the signal
        """
        if sig_num == signal.SIGUSR1:
            self.onUpdate()
            signal.signal(signal.SIGUSR1, self._receiveSignal) # Update signal
        elif sig_num == signal.SIGTERM:
            self.onShutdown()
        else:
            message = 'Unknown signal: {}'.format(sig_num)
            self.log.error(message)
    
    # ..........................................................................

    # ============================
    # = Daemon control functions =
    # ============================
    # ............................. 
Example 11
Project: myhoard   Author: aiven   File: myhoard.py    Apache License 2.0 6 votes vote down vote up
def _restart_process(self, *, mysqld_options):
        # When not using systemd and we haven't started mysqld (during current invocation of the daemon)
        # start by determining current pid (if any) of the process so that we can kill it before starting.
        if self.mysqld_pid is None:
            self.mysqld_pid = detect_running_process_id(" ".join(self.config["start_command"])) or -1
        if self.mysqld_pid and self.mysqld_pid > 0:
            self.log.info("Terminating running mysqld process %s", self.mysqld_pid)
            os.kill(self.mysqld_pid, signal.SIGTERM)
            os.waitpid(self.mysqld_pid, 0)
            self.log.info("Process %s exited", self.mysqld_pid)
            self.mysqld_pid = -1

        full_command = self.config["start_command"] + mysqld_options
        self.log.info("Starting process %r", full_command)
        proc = subprocess.Popen(full_command, env={"MYSQLD_OPTS": " ".join(mysqld_options)})
        self.mysqld_pid = proc.pid
        self.log.info("Process %r started, pid %s", full_command, proc.pid) 
Example 12
Project: alfred-urban-dictionary   Author: xilopaint   File: background.py    MIT License 6 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 13
Project: vulnerability-engine   Author: RedHatInsights   File: platform_mock.py    GNU General Public License v2.0 6 votes vote down vote up
def main():
    """Main platform mock entrypoint."""
    init_logging()
    if not os.path.exists(STORAGE_PATH):
        os.makedirs(STORAGE_PATH)
    LOGGER.info("Starting platform mock.")
    app = ServerApplication()
    app.listen(8000)

    def terminate(*_):
        """Trigger shutdown."""
        LOGGER.info("Signal received, stopping application.")
        IOLoop.instance().add_callback_from_signal(app.stop)

    signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
    for sig in signals:
        signal.signal(sig, terminate)

    app.start()
    LOGGER.info("Shutting down.") 
Example 14
Project: vulnerability-engine   Author: RedHatInsights   File: vmaas_sync.py    GNU General Public License v2.0 6 votes vote down vote up
def main():
    """Main VMaaS listener entrypoint."""
    start_http_server(int(PROMETHEUS_PORT))
    init_logging()
    LOGGER.info("Starting VMaaS sync service.")
    with DatabasePool(1):
        app = ServerApplication()
        app.listen(8000)

        def terminate(*_):
            """Trigger shutdown."""
            LOGGER.info("Signal received, stopping application.")
            IOLoop.instance().add_callback_from_signal(app.stop)

        signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
        for sig in signals:
            signal.signal(sig, terminate)

        app.start()
    LOGGER.info("Shutting down.") 
Example 15
Project: PathDump   Author: PathDump   File: tcpmon.py    Apache License 2.0 6 votes vote down vote up
def monitor_retransmit():
    global proc

    with proc.stdout:
        for line in iter (proc.stdout.readline, b''):
            if stop_flag:
                break

            tokens = line.split()
            if len(tokens) < 5 or (tokens[2] == '-:-' and tokens[4] == '-:-') \
                    or tokens[0] == "TIME":
                continue

            key = tokens[1] + ':' + tokens[3] + ':6'

            mon_lock.acquire()
            if key not in mon_flows:
                print "updating mon_flows", key
                mon_flows.update ({key: 1})
            mon_lock.release()

    os.kill (proc.pid, signal.SIGTERM)
    proc.wait() # wait for the subprocess to exit
    proc = None 
Example 16
Project: python-ble-example   Author: sotiris-oikonomou   File: Gattadvertiser.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    GObject.threads_init()

    # Catch SIGTERM and do a normal exit
    signal(SIGTERM, signal_handle)

    logger = logging.getLogger("rotating.logger")
    log_file_bytes = 1048576 * 5
    log_files = 3
    logging_file = '/var/log/GattLogs/Gattadvertiser.log'
    logger.setLevel(logging.DEBUG)
    rotating_handler = RotatingFileHandler(logging_file, maxBytes=log_file_bytes, backupCount=log_files)
    logger.addHandler(rotating_handler)
    logger.debug('[%s] ----NEW RUN----', time.strftime('%d/%m %H:%M:%S'))

    global mainloop

    logger.debug('[%s] Initialising Gatt Advertiser', time.strftime('%d/%m %H:%M:%S'))
    gatt_advertiser_thread = threading.Thread(target=run_gatt_advertiser)
    gatt_advertiser_thread.start()

    gatt_advertiser_thread.join() 
Example 17
Project: shepherd   Author: geissdoerfer   File: cli.py    MIT License 6 votes vote down vote up
def rpc(port):

    shepherd_io = ShepherdDebug()
    shepherd_io.__enter__()
    logger.debug("Initialized shepherd debug interface")
    time.sleep(1)

    server = zerorpc.Server(shepherd_io)
    server.bind(f"tcp://0.0.0.0:{ port }")
    time.sleep(1)

    def stop_server():
        server.stop()
        shepherd_io.__exit__()
        sys.exit(0)

    gevent.signal(signal.SIGTERM, stop_server)
    gevent.signal(signal.SIGINT, stop_server)

    shepherd_io.start()
    logger.debug("Started shepherd debug interface")
    server.run() 
Example 18
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def send_signal(self, sig):
        """Send a signal to process pre-emptively checking whether
        PID has been reused (see signal module constants) .
        On Windows only SIGTERM is valid and is treated as an alias
        for kill().
        """
        if _POSIX:
            self._send_signal(sig)
        else:
            if sig == signal.SIGTERM:
                self._proc.kill()
            else:
                raise ValueError("only SIGTERM is supported on Windows") 
Example 19
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def terminate(self):
        """Terminate the process with SIGTERM pre-emptively checking
        whether PID has been reused.
        On Windows this is an alias for kill().
        """
        if _POSIX:
            self._send_signal(signal.SIGTERM)
        else:
            self._proc.kill() 
Example 20
Project: pyblish-win   Author: pyblish   File: subprocess.py    GNU Lesser 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 21
Project: pyblish-win   Author: pyblish   File: subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def terminate(self):
            """Terminate the process with SIGTERM
            """
            self.send_signal(signal.SIGTERM) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_signal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_issue9324(self):
        # Updated for issue #10003, adding SIGBREAK
        handler = lambda x, y: None
        for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
                    signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
                    signal.SIGTERM):
            # Set and then reset a handler for signals that work on windows
            signal.signal(sig, signal.signal(sig, handler))

        with self.assertRaises(ValueError):
            signal.signal(-1, handler)

        with self.assertRaises(ValueError):
            signal.signal(7, handler) 
Example 23
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_send_signal(self):
        self._kill_process('send_signal', signal.SIGTERM) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_send_signal_dead(self):
        self._kill_dead_process('send_signal', signal.SIGTERM) 
Example 25
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_kill_sigterm(self):
        # SIGTERM doesn't mean anything special, but make sure it works
        self._kill(signal.SIGTERM) 
Example 26
Project: pyblish-win   Author: pyblish   File: forking.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def terminate(self):
            if self.returncode is None:
                try:
                    os.kill(self.pid, signal.SIGTERM)
                except OSError, e:
                    if self.wait(timeout=0.1) is None:
                        raise 
Example 27
Project: pyblish-win   Author: pyblish   File: PyShell.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def unix_terminate(self):
        "UNIX: make sure subprocess is terminated and collect status"
        if hasattr(os, 'kill'):
            try:
                os.kill(self.rpcpid, SIGTERM)
            except OSError:
                # process already terminated:
                return
            else:
                try:
                    os.waitpid(self.rpcpid, 0)
                except OSError:
                    return 
Example 28
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: serving.py    Apache License 2.0 5 votes vote down vote up
def initiate_shutdown(self):
        """A horrible, horrible way to kill the server for Python 2.6 and
        later.  It's the best we can do.
        """
        # Windows does not provide SIGKILL, go with SIGTERM then.
        sig = getattr(signal, 'SIGKILL', signal.SIGTERM)
        # reloader active
        if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
            os.kill(os.getpid(), sig)
        # python 2.7
        self.server._BaseServer__shutdown_request = True
        # python 2.6
        self.server._BaseServer__serving = False 
Example 29
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: serving.py    Apache License 2.0 5 votes vote down vote up
def initiate_shutdown(self):
        """A horrible, horrible way to kill the server for Python 2.6 and
        later.  It's the best we can do.
        """
        # Windows does not provide SIGKILL, go with SIGTERM then.
        sig = getattr(signal, 'SIGKILL', signal.SIGTERM)
        # reloader active
        if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
            os.kill(os.getpid(), sig)
        # python 2.7
        self.server._BaseServer__shutdown_request = True
        # python 2.6
        self.server._BaseServer__serving = False 
Example 30
Project: kvmd   Author: pikvm   File: server.py    GNU General Public License v3.0 5 votes vote down vote up
def __run_system_task(self, method: Callable, *args: Any) -> None:
        async def wrapper() -> None:
            try:
                await method(*args)
                raise RuntimeError(f"Dead system task: {method.__name__}"
                                   f"({', '.join(getattr(arg, '__name__', str(arg)) for arg in args)})")
            except asyncio.CancelledError:
                pass
            except Exception:
                get_logger().exception("Unhandled exception, killing myself ...")
                os.kill(os.getpid(), signal.SIGTERM)
        self.__system_tasks.append(asyncio.create_task(wrapper())) 
Example 31
Project: AutoDL   Author: tanguofu   File: reloader_helpers.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def watchdog(sleep_interval):
    """Watch project files, restart worker process if a change happened.

    :param sleep_interval: interval in second.
    :return: Nothing
    """
    mtimes = {}
    worker_process = restart_with_reloader()
    signal.signal(
        signal.SIGTERM, lambda *args: kill_program_completly(worker_process))
    signal.signal(
        signal.SIGINT, lambda *args: kill_program_completly(worker_process))
    while True:
        for filename in _iter_module_files():
            try:
                mtime = os.stat(filename).st_mtime
            except OSError:
                continue

            old_time = mtimes.get(filename)
            if old_time is None:
                mtimes[filename] = mtime
                continue
            elif mtime > old_time:
                kill_process_children_unix(worker_process.pid)
                worker_process = restart_with_reloader()

                mtimes[filename] = mtime
                break

        sleep(sleep_interval) 
Example 32
Project: reroils-data-legacy   Author: rero   File: test_examples_app.py    GNU General Public License v2.0 5 votes vote down vote up
def example_app():
    """Example app fixture."""
    current_dir = os.getcwd()

    # Go to example directory
    project_dir = dirname(dirname(abspath(__file__)))
    exampleapp_dir = join(project_dir, 'examples')
    os.chdir(exampleapp_dir)

    # Setup application
    assert subprocess.call('./app-setup.sh', shell=True) == 0

    # Setup fixtures
    assert subprocess.call('./app-fixtures.sh', shell=True) == 0

    # Start example app
    webapp = subprocess.Popen(
        'FLASK_APP=app.py flask run --debugger -p 5001',
        stdout=subprocess.PIPE, preexec_fn=os.setsid, shell=True)
    time.sleep(10)
    yield webapp

    # Stop server
    os.killpg(webapp.pid, signal.SIGTERM)

    # Tear down example app
    subprocess.call('./app-teardown.sh', shell=True)

    # Return to the original directory
    os.chdir(current_dir)


# def test_example_app_role_admin(example_app):
#     """Test example app."""
#     cmd = 'curl http://0.0.0.0:5001/'
#     output = subprocess.check_output(cmd, shell=True)
#     assert b'Welcome to REROILS-DATA' in output 
Example 33
Project: sandsifter   Author: Battelle   File: sifter.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def stop(self):
        if self.process:
            try:
                os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
            except OSError:
                pass 
Example 34
Project: flasky   Author: RoseOu   File: serving.py    MIT License 5 votes vote down vote up
def initiate_shutdown(self):
        """A horrible, horrible way to kill the server for Python 2.6 and
        later.  It's the best we can do.
        """
        # Windows does not provide SIGKILL, go with SIGTERM then.
        sig = getattr(signal, 'SIGKILL', signal.SIGTERM)
        # reloader active
        if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
            os.kill(os.getpid(), sig)
        # python 2.7
        self.server._BaseServer__shutdown_request = True
        # python 2.6
        self.server._BaseServer__serving = False 
Example 35
Project: flasky   Author: RoseOu   File: arbiter.py    MIT License 5 votes vote down vote up
def handle_term(self):
        "SIGTERM handling"
        raise StopIteration 
Example 36
Project: flasky   Author: RoseOu   File: arbiter.py    MIT License 5 votes vote down vote up
def handle_winch(self):
        "SIGWINCH handling"
        if self.cfg.daemon:
            self.log.info("graceful stop of workers")
            self.num_workers = 0
            self.kill_workers(signal.SIGTERM)
        else:
            self.log.debug("SIGWINCH ignored. Not daemonized") 
Example 37
Project: core   Author: lifemapper   File: daemon.py    GNU General Public License v3.0 5 votes vote down vote up
def stop(self):
        """Stop the daemon
        """
        # Get the pid from the pidfile
        try:
            pid = None
            with open(self.pidfile) as in_pid:
                pid = int(in_pid.read().strip())
        except IOError:
            pass
        
        if not pid:
            msg = 'pidfile {} does not exist. Daemon not running?'.format(
                self.pidfile)
            self.log.error(msg)
            return # not an error in a restart
        
        # Try killing the daemon process         
        try:
            max_time = 60  # Try to kill process for 60 seconds
            wait_time = 0
            while os.path.exists(self.pidfile) and wait_time < max_time:
                os.kill(pid, signal.SIGTERM)
                time.sleep(5)
                wait_time += 5
            if wait_time >= max_time and os.path.exists(self.pidfile):
                raise Exception('Could not kill process: {}'.format(pid))
        except OSError as os_err:
            err = str(os_err)
            if err.find("No such process") > 0:
                if os.path.exists(self.pidfile):
                    os.remove(self.pidfile)
            else:
                self.log.error(str(err))
                sys.exit(1)
    
    # ............................. 
Example 38
Project: core   Author: lifemapper   File: subprocessManager.py    GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        """Run the command

        Returns:
            exit status code, standard error
        """
        stdErr = None
        self.myProc = Popen(
            self.cmd, shell=True, stderr=PIPE, preexec_fn=os.setsid)
        pid = self.myProc.pid
        self._wait()
        runTime = 0
        while self.myProc.poll() is None and \
                runTime < self.killTime and pid_exists(pid):
            self._wait()
            # Get std err.  This bumps process in case of immediate fail of
            #    Maxent
            _ = self.myProc.stderr.read()
            runTime += self.waitTime
            
        if runTime >= self.killTime:
            self.signal(signal.SIGTERM)
            raise LongRunningProcessError(
                'Process took too long to run (> {} seconds)'.format(
                    self.killTime))
            
        # Get output
        exitCode = self.myProc.poll()
        if self.myProc.stderr is not None:
            stdErr = self.myProc.stderr.read()
        return exitCode, stdErr
    
    # ............................. 
Example 39
Project: core   Author: lifemapper   File: boomer.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, configFname, successFname, log=None):      
        self.name = self.__class__.__name__.lower()
        # Logfile
        if log is None:
            secs = time.time()
            timestamp = "{}".format(time.strftime("%Y%m%d-%H%M", time.localtime(secs)))
            logname = '{}.{}'.format(self.name, timestamp)
            log = ScriptLogger(logname, level=logging.INFO)
        self.log = log
        
        self.configFname = configFname
        self._successFname = successFname
        
#         self.do_intersect = None
        self.do_pam_stats = None 
        self.do_mcpa = None 
        # Send Database connection
        self._scribe = BorgScribe(self.log)
        # iterator tool for species
        self.christopher = None

#         # Dictionary of {scenCode: (potatoChain, triagePotatoFile)}
#         self.potatoes = None

        # MFChain for lots of spuds 
        self.potatoBushel = None
        self.squidNames = None
        # Stop indicator
        self.keepWalken = False
        
        signal.signal(signal.SIGTERM, self._receiveSignal) # Stop signal

    # ............................. 
Example 40
Project: core   Author: lifemapper   File: mattDaemon.py    GNU General Public License v3.0 5 votes vote down vote up
def stop_catalog_server(self):
        """Stop the local catalog server
        """
        self.log.debug('Stopping catalog server')
        os.killpg(os.getpgid(self.cs_proc.pid), signal.SIGTERM)
    
    # ............................. 
Example 41
Project: core   Author: lifemapper   File: mattDaemon.py    GNU General Public License v3.0 5 votes vote down vote up
def stop_worker_factory(self):
        """Kill worker factory
        """
        self.log.debug('Kill worker factory')
        os.killpg(os.getpgid(self.wf_proc.pid), signal.SIGTERM)
    
    # ............................. 
Example 42
Project: myhoard   Author: aiven   File: myhoard.py    Apache License 2.0 5 votes vote down vote up
def request_shutdown(self, is_signal=True, _frame=None):
        if is_signal:
            self.log.info("Got SIGINT or SIGTERM signal, shutting down")
        self.loop.stop() 
Example 43
Project: myhoard   Author: aiven   File: myhoard.py    Apache License 2.0 5 votes vote down vote up
def run(self):
        self.loop.add_signal_handler(signal.SIGHUP, self.request_reload)
        self.loop.add_signal_handler(signal.SIGINT, self.request_shutdown)
        self.loop.add_signal_handler(signal.SIGTERM, self.request_shutdown)
        self.loop.run_until_complete(self._reload_and_initialize())

        self.loop.run_forever()
        self.loop.run_until_complete(self._stop())
        self.log.info("Exiting")

        return 0 
Example 44
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: xvp.py    Apache License 2.0 5 votes vote down vote up
def _xvp_stop(self):
        LOG.debug('Stopping xvp')
        pid = self._xvp_pid()
        if not pid:
            return
        try:
            os.kill(pid, signal.SIGTERM)
        except OSError:
            # if it's already not running, no problem.
            pass 
Example 45
Project: i-portalen   Author: I-sektionen   File: grunt.py    MIT License 5 votes vote down vote up
def kill_grunt_process(pid):
    print('>>> Closing grunt process')
    os.kill(pid, signal.SIGTERM) 
Example 46
Project: PyBoof   Author: lessthanoptimal   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def shutdown_jvm():
    global java_pid, gateway
    if java_pid is None:
        pass
    else:
        # shutdown the gateway so that it doesn't spew out a billion error messages when it can't connect
        # to the JVM
        gateway.shutdown()
        gateway = None
        os.kill(java_pid, signal.SIGTERM)
        java_pid = None


# Catch control-c and kill the java process "gracefully" first. 
Example 47
Project: polish-sentence-evaluation   Author: sdadas   File: analyzer.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.analyzer: PopenSpawn = self.__run_analyzer()
        self.analyzer.delimiter = "\n"
        atexit.register(lambda: self.analyzer.kill(signal.SIGTERM)) 
Example 48
Project: trunklucator   Author: Dumbris   File: trunklucator.py    Apache License 2.0 5 votes vote down vote up
def signal_handler(loop):
    loop.remove_signal_handler(signal.SIGTERM)
    #is_working = False 
Example 49
Project: trunklucator   Author: Dumbris   File: trunklucator.py    Apache License 2.0 5 votes vote down vote up
def start_thread(self):
        self.aiothread = AioThread()
        self.loop = self.aiothread.get_loop()
        #self.loop.add_signal_handler(signal.SIGTERM, signal_handler, self.loop)
        self.ws = WebServer(loop=self.loop, *self.args, **self.kwargs)
        self.aiothread.set_server(self.ws)
        self.aiothread.start()
        self.aiothread.event.wait() 
Example 50
Project: safe_pool   Author: jmavila   File: safe_pool.py    GNU General Public License v2.0 5 votes vote down vote up
def _join_exited_workers(self):
        """Extends pool _join_exited_workers. 
        Detects When a worker is killed by either SIGKILL, SIGTERM, SIGSEGV, SIGNIT or SIGPIPE
        If the pool is set to retry it will put in the input queue the pending task to re-execute it
        Else, the left counter is decremented so the pool can finish its execution in a normal way
        """
        cleaned = False
        for i in reversed(range(len(self._pool))):
            worker = self._pool[i]
            debug('Worker {} exitcode: {}'.format(worker.name, worker.exitcode))
            if worker.exitcode is not None:
                debug('cleaning up worker %d' % i)
                worker.join()
                if abs(worker.exitcode) in HANDLED_SIGNALS:
                    debug('*'*10)
                    debug(str(HANDLED_SIGNALS))
                    debug('Worker died: ' + str(worker.name))
                    pending_task = self._worker_tasks_log.get(worker.name)
                    if self._retry_killed_tasks:
                        debug('It was assigned to task: ' + str(pending_task))
                        if pending_task:
                            debug('Retrying task: ' + str(pending_task))
                            try:
                                self._quick_put(pending_task)
                            except IOError:
                                debug('could not put task on queue')
                                break

                    elif self._cache and len(self._cache) == 1:  # just skip the result
                            cache_index = list(self._cache)[0]
                            debug('Skipping result of faulty worker: ' + str(worker.name))
                            if self._abort_when_killed:
                                self._cache[cache_index].abort_workers()
                            else:
                                self._cache[cache_index].handle_killed_worker()
                cleaned = True
                del self._pool[i]
        return cleaned