Python signal.SIGKILL Examples

The following are 30 code examples for showing how to use signal.SIGKILL(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module signal , or try the search function .

Example 1
Project: pgcli   Author: dbcli   File: environment.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def after_scenario(context, scenario):
    """Cleans up after each scenario completes."""
    if hasattr(context, "cli") and context.cli and not context.exit_sent:
        # Quit nicely.
        if not context.atprompt:
            dbname = context.currentdb
            context.cli.expect_exact("{0}> ".format(dbname), timeout=15)
        context.cli.sendcontrol("c")
        context.cli.sendcontrol("d")
        try:
            context.cli.expect_exact(pexpect.EOF, timeout=15)
        except pexpect.TIMEOUT:
            print("--- after_scenario {}: kill cli".format(scenario.name))
            context.cli.kill(signal.SIGKILL)
    if hasattr(context, "tmpfile_sql_help") and context.tmpfile_sql_help:
        context.tmpfile_sql_help.close()
        context.tmpfile_sql_help = None


# # TODO: uncomment to debug a failure
# def after_step(context, step):
#     if step.status == "failed":
#         import pdb; pdb.set_trace() 
Example 2
Project: ffw   Author: dobin   File: verifier.py    License: 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 3
Project: pulseaudio-dlna   Author: masmu   File: chromecast-beam.py    License: GNU General Public License v3.0 6 votes vote down vote up
def do_GET(self):
        client_address = self.client_address[0]
        logger.info('Serving transcoded media file to {} ...'.format(
            client_address))

        self.send_head()
        path = self.translate_path(self.path)
        command = VLCEncoderSettings.command(path)
        logger.info('Launching {}'.format(command))

        try:
            with open(os.devnull, 'w') as dev_null:
                encoder_process = subprocess.Popen(
                    command, stdout=subprocess.PIPE, stderr=dev_null)
                shutil.copyfileobj(encoder_process.stdout, self.wfile)
        except:
            logger.info('Connection from {} closed.'.format(client_address))
            logger.debug(traceback.format_exc())
        finally:
            pid = encoder_process.pid
            logger.info('Terminating process {}'.format(pid))
            try:
                os.kill(pid, signal.SIGKILL)
            except:
                pass 
Example 4
Project: browserscope   Author: elsigh   File: dev_appserver_multiprocess.py    License: Apache License 2.0 6 votes vote down vote up
def PosixShutdown():
  """Kills a posix process with os.kill."""
  dev_process = GlobalProcess()
  children = dev_process.Children()
  for term_signal in (signal.SIGTERM, signal.SIGKILL):
    for child in children:
      if child.process is None:
        continue
      if child.process.returncode is not None:
        continue
      pid = child.process.pid
      try:
        logging.debug('posix kill %d with signal %d', pid, term_signal)
        os.kill(pid, term_signal)
      except OSError, err:
        logging.error('Error encountered sending pid %d signal %d:%s\n',
                      pid, term_signal, err)
        break

    time.sleep(0.2) 
Example 5
Project: jbox   Author: jpush   File: arbiter.py    License: 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)
        """

        if self.reexec_pid == 0 and self.master_pid == 0:
            for l in self.LISTENERS:
                l.close()

        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 6
Project: jbox   Author: jpush   File: arbiter.py    License: MIT License 6 votes vote down vote up
def murder_workers(self):
        """\
        Kill unused/idle workers
        """
        if not self.timeout:
            return
        workers = list(self.WORKERS.items())
        for (pid, worker) in workers:
            try:
                if time.time() - worker.tmp.last_update() <= self.timeout:
                    continue
            except (OSError, ValueError):
                continue

            if not worker.aborted:
                self.log.critical("WORKER TIMEOUT (pid:%s)", pid)
                worker.aborted = True
                self.kill_worker(pid, signal.SIGABRT)
            else:
                self.kill_worker(pid, signal.SIGKILL) 
Example 7
Project: westpa   Author: westpa   File: worker.py    License: MIT License 6 votes vote down vote up
def __init__(self, rr_endpoint, ann_endpoint):
        super(ZMQWorker,self).__init__()
        
        # Upstream endpoints
        self.rr_endpoint = rr_endpoint
        self.ann_endpoint = ann_endpoint
                
        # Downstream endpoints
        self.task_endpoint = self.make_internal_endpoint()
        self.result_endpoint = self.make_internal_endpoint()
        
        self.master_id = None
        self.identified = False
        
        # The task currently being processed
        self.pending_task = None
        
        # Executor process
        
        self.shutdown_timeout = 5.0 # Five second wait between shutdown message and SIGINT and SIGINT and SIGKILL
        self.executor_process = None 
Example 8
Project: cf-mendix-buildpack   Author: mendix   File: start.py    License: Apache License 2.0 6 votes vote down vote up
def terminate_process():
    if m2ee:
        logging.info("stopping app...")
        if not m2ee.stop():
            if not m2ee.terminate():
                m2ee.kill()
    try:
        this_process = os.getpgid(0)
        logging.debug(
            "Terminating process group with pgid=%s", format(this_process)
        )
        os.killpg(this_process, signal.SIGTERM)
        time.sleep(3)
        os.killpg(this_process, signal.SIGKILL)
    except OSError:
        logging.exception("Failed to terminate all child processes") 
Example 9
Project: benchexec   Author: sosy-lab   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def kill_process(pid, sig=None):
    """Try to send signal to given process."""
    if sig is None:
        sig = signal.SIGKILL  # set default lazily, otherwise importing fails on Windows
    try:
        os.kill(pid, sig)
    except OSError as e:
        if e.errno == errno.ESRCH:
            # process itself returned and exited before killing
            logging.debug(
                "Failure %s while killing process %s with signal %s: %s",
                e.errno,
                pid,
                sig,
                e.strerror,
            )
        else:
            logging.warning(
                "Failure %s while killing process %s with signal %s: %s",
                e.errno,
                pid,
                sig,
                e.strerror,
            ) 
Example 10
Project: avocado-vt   Author: avocado-framework   File: migration.py    License: GNU General Public License v2.0 6 votes vote down vote up
def do_cancel(self, sig=signal.SIGKILL):
        """
        Kill process during migration.

        :param sig: The signal to send
        :raise: test.error when kill fails
        """
        def _get_pid():
            cmd = "ps aux |grep 'virsh .*migrate' |grep -v grep |awk '{print $2}'"
            pid = process.run(cmd, shell=True).stdout_text
            return pid

        pid = utils_misc.wait_for(_get_pid, 30)
        if utils_misc.safe_kill(pid, sig):
            logging.info("Succeed to cancel migration: [%s].", pid.strip())
        else:
            raise exceptions.TestError("Fail to cancel migration: [%s]"
                                       % pid.strip()) 
Example 11
Project: vnpy_crypto   Author: birforce   File: test_process.py    License: MIT License 6 votes vote down vote up
def test_wait_timeout_0(self):
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        self.assertRaises(psutil.TimeoutExpired, p.wait, 0)
        p.kill()
        stop_at = time.time() + 2
        while True:
            try:
                code = p.wait(0)
            except psutil.TimeoutExpired:
                if time.time() >= stop_at:
                    raise
            else:
                break
        if POSIX:
            self.assertEqual(code, -signal.SIGKILL)
        else:
            self.assertEqual(code, signal.SIGTERM)
        self.assertFalse(p.is_running()) 
Example 12
Project: iSDX   Author: sdn-ixp   File: faucet_util.py    License: Apache License 2.0 5 votes vote down vote up
def kill_on_exception(logname):
    """decorator to ensure functions will kill ryu when an unhandled exception
    occurs"""
    def _koe(func):
        @wraps(func)
        def __koe(*args, **kwargs):
            try:
                func(*args, **kwargs)
            except:
                logging.getLogger(logname).exception(
                    "Unhandled exception, killing RYU")
                logging.shutdown()
                os.kill(os.getpid(), signal.SIGKILL)
        return __koe
    return _koe 
Example 13
Project: Paradrop   Author: ParadropLabs   File: log_provider.py    License: Apache License 2.0 5 votes vote down vote up
def detach(self):
        """
        Stop listening for log messages.

        After this is called, no additional messages will be added to the
        queue.
        """
        if self.listening:
            # We have to kill the process explicitly with SIGKILL,
            # terminate() function does not work here.
            for process in self.processes:
                os.kill(process.pid, signal.SIGKILL)

            self.processes = []
            self.listening = False 
Example 14
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: take_backup.py    License: MIT License 5 votes vote down vote up
def check_kill_process(pstring):
        # Static method for killing given processes
        for line in os.popen("ps ax | grep " + pstring + " | grep -v grep"):
            fields = line.split()
            pid = fields[0]
            if pid:
                os.kill(int(pid), signal.SIGKILL) 
Example 15
Project: jawfish   Author: war-and-code   File: subprocess.py    License: MIT License 5 votes vote down vote up
def kill(self):
            """Kill the process with SIGKILL
            """
            self.send_signal(signal.SIGKILL) 
Example 16
Project: me-ica   Author: ME-ICA   File: pp_support.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def kill_slaves(slave_kill_filename):
    """Kill all remote slaves which are stored in the given file.

    This functions is only meant for emergency situations, when something
    went wrong and the slaves have to be killed manually.
    """
    with open(slave_kill_filename) as tempfile:
        for line in tempfile:
            address, pid, ssh_pid = line.split(":")
            pid = int(pid)
            ssh_pid = int(ssh_pid)
            # open ssh connection to to kill remote slave
            proc = subprocess.Popen(["ssh","-T", address],
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT)
            proc.stdin.write("kill %d\n" % pid)
            proc.stdin.flush()
            # kill old ssh connection
            try:
                os.kill(ssh_pid, signal.SIGKILL)
            except:
                pass
            # a kill might prevent the kill command transmission
            # os.kill(proc.pid, signal.SIGQUIT)
            print "killed slave " + address + " (pid %d)" % pid
        print "all slaves killed." 
Example 17
Project: Zopkio   Author: linkedin   File: deployer.py    License: Apache License 2.0 5 votes vote down vote up
def kill(self, unique_id, configs=None):
    """ Issues a kill -9 to the specified process
    calls the deployers get_pid function for the process. If no pid_file/pid_keyword is specified
    a generic grep of ps aux command is executed on remote machine based on process parameters
    which may not be reliable if more process are running with similar name

    :Parameter unique_id: the name of the process
    """
    self._send_signal(unique_id, signal.SIGKILL, configs) 
Example 18
Project: python-podman   Author: containers   File: test_containers.py    License: Apache License 2.0 5 votes vote down vote up
def test_kill(self):
        self.assertTrue(self.alpine_ctnr.running)
        ctnr = self.alpine_ctnr.kill(signal.SIGKILL)
        self.assertFalse(ctnr.running) 
Example 19
Project: PythonClassBook   Author: PythonClassRoom   File: fig18_15.py    License: GNU General Public License v3.0 5 votes vote down vote up
def parentInterruptHandler( signum, frame ):
   global pid
   global parentKeepRunning

   # send kill signal to child process and exit
   os.kill( pid, signal.SIGKILL )  # send kill signal
   print "Interrupt received. Child process killed."

   # allow parent process to terminate normally
   parentKeepRunning = 0

# set parent's handler for SIGINT 
Example 20
Project: recipes-py   Author: luci   File: subproc.py    License: Apache License 2.0 5 votes vote down vote up
def _kill(proc, gid):
    """Kills the process in group `gid` as gracefully as possible:

      * Send SIGTERM to the process group.
        * This is a bit atypical for POSIX, but this is done to provide
          consistent behavior between *nix/Windows (where we MUST signal the
          whole group). This allows writing parent/child programs which run
          cross-platform without requiring per-platform parent/child handling
          code.
        * If programs really don't want this, they should make their own process
          group for their children.
      * Give main process 30s to quit.
      * Send SIGKILL to the whole group (to avoid leaked processes). This will
        kill the process we spawned directly.

    Returns the process's returncode.
    """
    try:
      os.killpg(gid, signal.SIGTERM)
    except OSError:
      pass
    # TODO(iannucci): This API changes in python3 to raise an exception on
    # timeout.
    proc.wait(timeout=30)
    try:
      os.killpg(gid, signal.SIGKILL)
    except OSError:
      pass
    return proc.wait() 
Example 21
Project: gipc   Author: jgehrcke   File: test_gipc.py    License: MIT License 5 votes vote down vote up
def test_exitcode_sigkill(self):
        p = start_process(p_child_b)
        p.join()
        if not WINDOWS:
            assert p.exitcode == -signal.SIGKILL
        else:
            assert p.exitcode == 1
        _call_close_method_if_exists(p) 
Example 22
Project: gipc   Author: jgehrcke   File: test_gipc.py    License: MIT License 5 votes vote down vote up
def p_child_b():
    if not WINDOWS:
        os.kill(os.getpid(), signal.SIGKILL)
    else:
        sys.exit(1) 
Example 23
Project: pulseaudio-dlna   Author: masmu   File: application.py    License: GNU General Public License v3.0 5 votes vote down vote up
def shutdown(self, signal_number=None, frame=None):
        if not self.is_terminating:
            print('Application is shutting down ...')
            self.is_terminating = True

            for process in self.processes:
                # We send SIGINT to all subprocesses to trigger
                # KeyboardInterrupt and exit the mainloop
                # in those which use GObject.MainLoop().
                # This unblocks the main thread and ensures that the process
                # is receiving signals again.
                os.kill(process.pid, signal.SIGINT)
                # SIGTERM is the acutal one which is terminating the process
                os.kill(process.pid, signal.SIGTERM)

            start_time = time.time()
            while True:
                if time.time() - start_time >= self.SHUTDOWN_TIMEOUT:
                    print('Terminating remaining subprocesses ...')
                    for process in self.processes:
                        if process is not None and process.is_alive():
                            os.kill(process.pid, signal.SIGKILL)
                    sys.exit(1)
                time.sleep(0.1)
                all_dead = True
                for process in self.processes:
                    if process.is_alive():
                        all_dead = False
                        break
                if all_dead:
                    break
            sys.exit(0) 
Example 24
Project: don   Author: CiscoSystems   File: path.py    License: Apache License 2.0 5 votes vote down vote up
def cleanup_processes(pid_list):
    pprint.pprint(pid_list)
    for pid in pid_list:
        try:
            os.kill(pid, signal.SIGKILL)
            status_update('Successfully killed pid: %d' % pid)
        except OSError:
            status_update('Process with pid: %d no longer exists' % pid)
            continue
    pass 
Example 25
Project: cassandra-dtest   Author: apache   File: bootstrap_test.py    License: Apache License 2.0 5 votes vote down vote up
def test_bootstrap_with_reset_bootstrap_state(self):
        """Test bootstrap with resetting bootstrap progress"""
        cluster = self.cluster
        cluster.set_configuration_options(values={'stream_throughput_outbound_megabits_per_sec': 1})
        cluster.populate(2).start(wait_other_notice=True)

        node1 = cluster.nodes['node1']
        node1.stress(['write', 'n=100K', '-schema', 'replication(factor=2)'])
        node1.flush()

        # kill node1 in the middle of streaming to let it fail
        t = InterruptBootstrap(node1)
        t.start()

        # start bootstrapping node3 and wait for streaming
        node3 = new_node(cluster)
        try:
            node3.start()
        except NodeError:
            pass  # node doesn't start as expected
        t.join()
        node1.start()

        # restart node3 bootstrap with resetting bootstrap progress
        node3.stop(signal_event=signal.SIGKILL)
        mark = node3.mark_log()
        node3.start(jvm_args=["-Dcassandra.reset_bootstrap_progress=true"])
        # check if we reset bootstrap state
        node3.watch_log_for("Resetting bootstrap progress to start fresh", from_mark=mark)
        # wait for node3 ready to query
        node3.wait_for_binary_interface(from_mark=mark)

        # check if 2nd bootstrap succeeded
        assert_bootstrap_state(self, node3, 'COMPLETED') 
Example 26
Project: codimension   Author: SergeySatskiy   File: procfeedback.py    License: GNU General Public License v3.0 5 votes vote down vote up
def killProcess(pid):
    """Tries to kill the given process"""
    for signal in (SIGTERM, SIGINT, SIGHUP):
        if not isProcessAlive(pid):
            return

        try:
            os.kill(pid, signal)
        except OSError as excpt:
            if excpt.errno == errno.ESRCH:
                return  # Already dead
            raise
        time.sleep(0.5)

    # Could not kill gracefully, try harder
    startTime = time.time()
    while True:
        if not isProcessAlive(pid):
            return

        if time.time() - startTime >= 15:
            raise Exception("Cannot kill process (pid: " + str(pid) + ")")

        try:
            os.kill(pid, SIGKILL)
        except OSError as excpt:
            if excpt.errno == errno.ESRCH:
                return  # Already dead
            raise
        time.sleep(0.1) 
Example 27
Project: im   Author: grycap   File: ansible_launcher.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _kill_childs(self):
        for pid_str in self._get_childs():
            os.kill(int(pid_str), signal.SIGTERM)
        # assure to kill all the processes using KILL signal
        time.sleep(1)
        for pid_str in self._get_childs():
            os.kill(int(pid_str), signal.SIGKILL) 
Example 28
Project: im   Author: grycap   File: im_service.py    License: GNU General Public License v3.0 5 votes vote down vote up
def kill_childs():
    for pid_str in get_childs():
        os.kill(int(pid_str), signal.SIGTERM)
    # assure to kill all the processes using KILL signal
    time.sleep(1)
    for pid_str in get_childs():
        os.kill(int(pid_str), signal.SIGKILL) 
Example 29
Project: LuckyCAT   Author: fkie-cad   File: afl-luckycat.py    License: GNU General Public License v3.0 5 votes vote down vote up
def clean_up():
    print('Killing all afl-fuzz instances...')
    p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
    out, err = p.communicate()
    for line in out.splitlines():
        if b'afl-fuzz' in line:
            pid = int(line.split(None, 1)[0])
            os.kill(pid, signal.SIGKILL)
    try:
        subprocess.Popen('tmux kill-session -t luckycatAFL', shell=True, stdout=subprocess.PIPE)
    except ChildProcessError:
        pass 
Example 30
Project: funcX   Author: funcx-faas   File: endpoint.py    License: Apache License 2.0 5 votes vote down vote up
def stop_endpoint(name: str = typer.Argument("default", autocompletion=complete_endpoint_name)):
    """ Stops an endpoint using the pidfile

    """

    endpoint_dir = os.path.join(State.FUNCX_DIR, name)
    pid_file = os.path.join(endpoint_dir, "daemon.pid")

    if os.path.exists(pid_file):
        logger.debug(f"{name} has a daemon.pid file")
        pid = None
        with open(pid_file, 'r') as f:
            pid = int(f.read())
        # Attempt terminating
        try:
            logger.debug("Signalling process: {}".format(pid))
            os.kill(pid, signal.SIGTERM)
            time.sleep(0.1)
            os.kill(pid, signal.SIGKILL)
            time.sleep(0.1)
            # Wait to confirm that the pid file disappears
            if not os.path.exists(pid_file):
                logger.info("Endpoint <{}> is now stopped".format(name))

        except OSError:
            logger.warning("Endpoint {} could not be terminated".format(name))
            logger.warning("Attempting Endpoint {} cleanup".format(name))
            os.remove(pid_file)
            sys.exit(-1)
    else:
        logger.info("Endpoint <{}> is not active.".format(name))