Python signal.SIGKILL Examples

The following are 30 code examples of signal.SIGKILL(). 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: start.py    From cf-mendix-buildpack with Apache License 2.0 8 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 #2
Source File: dev_appserver_multiprocess.py    From browserscope with 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 #3
Source File: util.py    From benchexec with 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 #4
Source File: chromecast-beam.py    From pulseaudio-dlna with 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 #5
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 #6
Source File: worker.py    From westpa with 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 #7
Source File: arbiter.py    From jbox with 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 #8
Source File: arbiter.py    From jbox with 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 #9
Source File: test_process.py    From vnpy_crypto with 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 #10
Source File: migration.py    From avocado-vt with 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
Source File: job_util.py    From osspolice with GNU General Public License v3.0 5 votes vote down vote up
def kill(self):
        try:
            os.kill(self.child, signal.SIGKILL)
        except OSError: pass 
Example #12
Source File: test.py    From ACE with Apache License 2.0 5 votes vote down vote up
def stop_api_server(self):
        """Stops the API server if it's running."""
        if self.api_server_process is None:
            return

        import signal
        os.kill(self.api_server_process.pid, signal.SIGKILL)

        self.api_server_process.join()
        self.api_server_process = None 
Example #13
Source File: worker.py    From fairtest with Apache License 2.0 5 votes vote down vote up
def kill_workers(self, pids=None):
        pids_to_workers = self.pids_to_workers
        if pids is None:
            pids = list(pids_to_workers.keys())
        for pid in pids:
            try:
                worker = pids_to_workers[pid]
            except KeyError:
                print("No worker with pid {} found!".format(pid))
                continue
            os.kill(pid, signal.SIGKILL)
            worker.join()
            del pids_to_workers[pid] 
Example #14
Source File: process_server.py    From ACE with Apache License 2.0 5 votes vote down vote up
def stop(self):
        if self.child_process is None:
            logging.error("child process does not exist")
            return

        logging.info("shutting down process server pid {}...".format(self.child_process.pid))

        try:
            self.child_process.terminate()

            # connect to move it past the connect call
            # TODO do we need a sleep here ? (is the signal async?)
            try:
                s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                s.connect(self.unix_socket)
            except:
                logging.error("unable to connect to {} to close connection: {}".format(self.unix_socket, e))
            finally:
                try:
                    s.close()
                except:
                    pass

            self.child_process.join(5)
            if self.child_process.is_alive():
                raise RuntimeError("unable to stop child process {}".format(self.child_process.pid))
        except Exception as e:
            logging.error("unable to terminate child process pid {}: {}".format(self.child_process.pid, e))
            try:
                logging.warning("sending SIGKILL to {}".format(self.child_process.pid))
                os.kill(self.child_process.pid, signal.SIGKILL)
            except Exception as e:
                logging.error("unable to kill process {}: {}".format(self.child_process.pid, e))

        try:
            os.remove(self.unix_socket)
        except Exception as e:
            logging.error("unable to delete unix socket {}: {}".format(self.unix_socket, e))
            report_exception()

        logging.info("process server stopped") 
Example #15
Source File: service.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _stop():
    print(u'======stop========')
    # 在任务表删除定时计划
    operate_crontab("del")

    # 查询进程组id
    gpid = _status()
    if gpid:
        # 进程组存在,杀死进程
        import signal
        # 杀死进程组
        os.killpg(int(gpid), signal.SIGKILL)
        i = 0
        while _status():
            time.sleep(1)
            i += 1
            print(u'等待{}秒'.format(i))

        print(u'{}成功停止{}服务[gpid={}]'.format(datetime.now(), base_path,gpid))

        try:
            sendmail.sendmail(subject='Notification: {}目录下服务进程停止'.format(base_path),
                              msgcontent= '服务进程[gpid={}]停止'.format(gpid))
        except:
            print(u'发送通知邮件失败')
            pass
    else:
        print(u'{}服务进程没有运行'.format(base_path)) 
Example #16
Source File: minijail.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def kill(self):
    """Kill minijail and all child processes."""
    os.killpg(self.popen.pid, signal.SIGKILL) 
Example #17
Source File: job_util.py    From osspolice with GNU General Public License v3.0 5 votes vote down vote up
def kill(self):
        try:
            os.kill(self.child, signal.SIGKILL)
        except OSError:
            pass 
Example #18
Source File: job_util.py    From osspolice with GNU General Public License v3.0 5 votes vote down vote up
def kill(self):
        try:
            os.kill(self.child, signal.SIGKILL)
        except OSError:
            pass 
Example #19
Source File: circo.py    From circo with MIT License 5 votes vote down vote up
def kill_process(pstring):
    for line in os.popen("ps ax | grep " + pstring + " | grep -v grep"):
        fields = line.split()
        pid = fields[0]
        os.kill(int(pid), signal.SIGKILL)


# Build SNMP OID Fake config 
Example #20
Source File: __init__.py    From ACE with Apache License 2.0 5 votes vote down vote up
def handle_cancel_event(self):
        # kill the external process
        if self.external_process is not None:
            logging.debug("terminating external process {0}".format(self.external_process))
            try:
                os.killpg(self.external_process.pid, signal.SIGTERM)
                self.external_process.wait(5)
            except:
                logging.debug("killing external process {0}".format(self.external_process))
                try:
                    os.killpg(self.external_process.pid, signal.SIGKILL)
                    self.external_process.wait()
                except Exception as e:
                    logging.debug("unable to kill external process {0}: {1}".format(self.external_process, str(e)))
                    #report_exception() 
Example #21
Source File: openvswitch.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def clean(self):
        logging.debug("Killall ovsdb-server")
        utils_misc.signal_program("ovsdb-server")
        if utils_misc.program_is_alive("ovsdb-server"):
            utils_misc.signal_program("ovsdb-server", signal.SIGKILL)
        logging.debug("Killall ovs-vswitchd")
        utils_misc.signal_program("ovs-vswitchd")
        if utils_misc.program_is_alive("ovs-vswitchd"):
            utils_misc.signal_program("ovs-vswitchd", signal.SIGKILL) 
Example #22
Source File: process_server.py    From ACE with Apache License 2.0 5 votes vote down vote up
def cleanup(self):
        try:
            # make sure the socket is closed
            self.sock.close()
        except Exception as e:
            logging.error("unable to close socket connection: {}".format(e))
            report_exception()

        # make sure the process is dead and reaped
        try:
            if self.p:
                logging.warning("killing leftover child process pid {}".format(self.p.pid))
                os.killpg(os.getpgid(self.p.pid), signal.SIGKILL)
                #self.p.kill()
                self.p.wait()
        except Exception as e:
            logging.error("unable to kill leftover process: {}".format(e))
            report_exception()

        # make sure the reader threads are dead
        # not much we can do except report it
        if self.stdout_reader_thread and self.stdout_reader_thread.is_alive():
            logging.error("stdout reader thread is still alive (not good)")

        if self.stderr_reader_thread and self.stderr_reader_thread.is_alive():
            logging.error("stderr reader thread is still alive (not good)")

        # delete the stderr tempfile if it exists
        try:
            if self.stderr_fp:
                self.stderr_fp.close()
        except Exception as e:
            logging.error("unable to delete stderr tempfile: {}".format(e))
            report_exception() 
Example #23
Source File: test_subprocess.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_leak_fast_process_del_killed(self):
        # Issue #12650: on Unix, if Popen.__del__() was called before the
        # process exited, and the process got killed by a signal, it would never
        # be removed from subprocess._active, which triggered a FD and memory
        # leak.
        # spawn a Popen, delete its reference and kill it
        p = subprocess.Popen([sys.executable, "-c",
                              'import time;'
                              'time.sleep(3)'],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        self.addCleanup(p.stdout.close)
        self.addCleanup(p.stderr.close)
        ident = id(p)
        pid = p.pid
        del p
        os.kill(pid, signal.SIGKILL)
        # check that p is in the active processes list
        self.assertIn(ident, [id(o) for o in subprocess._active])

        # let some time for the process to exit, and create a new Popen: this
        # should trigger the wait() of p
        time.sleep(0.2)
        with self.assertRaises(EnvironmentError) as c:
            with subprocess.Popen(['nonexisting_i_hope'],
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE) as proc:
                pass
        # p should have been wait()ed on, and removed from the _active list
        self.assertRaises(OSError, os.waitpid, pid, 0)
        self.assertNotIn(ident, [id(o) for o in subprocess._active]) 
Example #24
Source File: test_subprocess.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_kill(self):
        p = self._kill_process('kill')
        _, stderr = p.communicate()
        self.assertStderrEqual(stderr, '')
        self.assertEqual(p.wait(), -signal.SIGKILL) 
Example #25
Source File: test_tempfile.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_process_awareness(self):
        # ensure that the random source differs between
        # child and parent.
        read_fd, write_fd = os.pipe()
        pid = None
        try:
            pid = os.fork()
            if not pid:
                # child process
                os.close(read_fd)
                os.write(write_fd, next(self.r).encode("ascii"))
                os.close(write_fd)
                # bypass the normal exit handlers- leave those to
                # the parent.
                os._exit(0)

            # parent process
            parent_value = next(self.r)
            child_value = os.read(read_fd, len(parent_value)).decode("ascii")
        finally:
            if pid:
                # best effort to ensure the process can't bleed out
                # via any bugs above
                try:
                    os.kill(pid, signal.SIGKILL)
                except EnvironmentError:
                    pass

                # Read the process exit status to avoid zombie process
                os.waitpid(pid, 0)

            os.close(read_fd)
            os.close(write_fd)
        self.assertNotEqual(child_value, parent_value) 
Example #26
Source File: subprocess.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def kill(self):
            """Kill the process with SIGKILL
            """
            self.send_signal(signal.SIGKILL) 
Example #27
Source File: rpc_terminal.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def signal_window_destroy(self, window):
		if self.child_pid is None:
			self.logger.error('signal_window_destory was called but the child pid is None')
			return
		if os.path.exists("/proc/{0}".format(self.child_pid)):
			self.logger.debug("sending sigkill to child process: {0}".format(self.child_pid))
			os.kill(self.child_pid, signal.SIGKILL) 
Example #28
Source File: subprocess.py    From meddle with MIT License 5 votes vote down vote up
def kill(self):
            """Kill the process with SIGKILL
            """
            self.send_signal(signal.SIGKILL) 
Example #29
Source File: run_all.py    From CalculiX-Examples with MIT License 5 votes vote down vote up
def kill_gv(self, name):
        try:
            plist = subprocess.check_output(['pidof', name])
            plist = plist.strip().decode().split()
            for pid in plist:
                os.kill(int(pid), signal.SIGKILL)

        # No such process
        except:
            pass


    # Check relpath from example folder to Scripts 
Example #30
Source File: vmdk_ops.py    From vsphere-storage-for-docker with Apache License 2.0 5 votes vote down vote up
def wait_ops_in_flight():
    # Wait for the event indicating all in-flight ops are drained
    eventReceived = opsCounter.wait(WAIT_OPS_TIMEOUT)
    if (eventReceived):
        logging.info("All in-flight operations are completed - exiting")
        os.kill(os.getpid(), signal.SIGKILL) # kill the main process
    else:
        logging.warn("In-flight operations are taking too long to complete - abandoning wait")