Python signal.SIGQUIT Examples

The following are 30 code examples for showing how to use signal.SIGQUIT(). 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: 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 2
Project: crowbar   Author: galkan   File: main.py    License: MIT License 6 votes vote down vote up
def vnclogin(self, ip, port, keyfile):
        vnc_cmd = "%s -passwd %s %s:%s" % (self.vncviewer_path, keyfile, ip, port)

        if self.args.verbose == 2:
            self.logger.output_file("CMD: %s" % vnc_cmd)

        proc = subprocess.Popen(shlex.split(vnc_cmd), shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        brute = "LOG-VNC: " + ip + ":" + str(port) + " - " + keyfile
        self.logger.log_file(brute)

        # For every line out
        for line in proc.stdout:
            # Is debug enabled
            if self.args.debug:
                self.logger.output_file(line.decode("utf-8").rstrip())

            if re.search(self.vnc_success, str(line)):
                os.kill(proc.pid, signal.SIGQUIT)
                result = bcolors.OKGREEN + "VNC-SUCCESS: " + bcolors.ENDC + bcolors.OKBLUE + ip + ":" + str(
                    port) + " - " + keyfile + bcolors.ENDC
                self.logger.output_file(result)
                Main.is_success = 1
                break 
Example 3
Project: sagemaker-tensorflow-serving-container   Author: aws   File: serve.py    License: Apache License 2.0 6 votes vote down vote up
def _stop(self, *args):  # pylint: disable=W0613
        self._state = 'stopping'
        log.info('stopping services')
        try:
            os.kill(self._nginx.pid, signal.SIGQUIT)
        except OSError:
            pass
        try:
            if self._gunicorn:
                os.kill(self._gunicorn.pid, signal.SIGTERM)
        except OSError:
            pass
        try:
            os.kill(self._tfs.pid, signal.SIGTERM)
        except OSError:
            pass

        self._state = 'stopped'
        log.info('stopped') 
Example 4
Project: naz   Author: komuw   File: sig.py    License: MIT License 6 votes vote down vote up
def _signal_handling(logger: logging.Logger, client: naz.Client) -> None:
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = asyncio.get_event_loop()

    try:
        for _signal in [signal.SIGHUP, signal.SIGQUIT, signal.SIGTERM]:
            loop.add_signal_handler(
                _signal,
                functools.partial(
                    asyncio.ensure_future,
                    _handle_termination_signal(logger=logger, _signal=_signal, client=client),
                ),
            )
    except ValueError as e:
        logger.log(
            logging.DEBUG,
            {
                "event": "naz.cli.signals",
                "stage": "end",
                "state": "this OS does not support the said signal",
                "error": str(e),
            },
        ) 
Example 5
Project: bash-lambda-layer   Author: gkrizek   File: compat.py    License: MIT License 6 votes vote down vote up
def ignore_user_entered_signals():
    """
    Ignores user entered signals to avoid process getting killed.
    """
    if is_windows:
        signal_list = [signal.SIGINT]
    else:
        signal_list = [signal.SIGINT, signal.SIGQUIT, signal.SIGTSTP]
    actual_signals = []
    for user_signal in signal_list:
        actual_signals.append(signal.signal(user_signal, signal.SIG_IGN))
    try:
        yield
    finally:
        for sig, user_signal in enumerate(signal_list):
            signal.signal(user_signal, actual_signals[sig]) 
Example 6
Project: code   Author: ActiveState   File: recipe-579074.py    License: MIT License 6 votes vote down vote up
def _install_signal_handlers(self):
        """Install signal handlers for the process.
        """

        self._log.info('Installing signal handlers')

        def handler(signum, _):
            """Signal handler.
            """

            self._log.info('Got signal %s', signum)
            self._stop_event.set()

        for sig in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM,
                    signal.SIGQUIT, signal.SIGABRT):

            signal.signal(sig, handler) 
Example 7
Project: levye   Author: PolymorhicCode   File: main.py    License: MIT License 6 votes vote down vote up
def openvpnlogin(self, host, username, password, brute_file, port):

		brute_file_name = brute_file.name
                brute_file.seek(0)

                openvpn_cmd = "%s --config %s --auth-user-pass %s --remote %s %s"% (self.openvpn_path, self.args.config, brute_file_name, host, port)
                proc = subprocess.Popen(shlex.split(openvpn_cmd), shell=False, stdout = subprocess.PIPE, stderr = subprocess.PIPE)

                brute =  "LOG: OPENVPN: " + host + ":" + username + ":" + password + ":" + brute_file_name + "\n"
                self.fd_log_file.write(brute)
                for line in iter(proc.stdout.readline, ''):
                        if re.search(self.vpn_success, line):
                                now = datetime.datetime.now()
                                result = "SUCCESS," + now.strftime("%Y-%m-%d %H:%M:%S") + "," + "OPENVPN," + host + "," + username + "," + password + "\n"
                                print result[:-1]
                                self.fd_output_file.write(result)
                                os.kill(proc.pid, signal.SIGQUIT)

                brute_file.close() 
Example 8
Project: Galaxy_Plugin_Bethesda   Author: TouwaStar   File: worker.py    License: MIT License 6 votes vote down vote up
def init_signals(self) -> None:
        # 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 9
Project: Flask-P2P   Author: chalasr   File: base.py    License: MIT License 6 votes vote down vote up
def init_signals(self):
        # reset signaling
        [signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS]
        # init new signaling
        signal.signal(signal.SIGQUIT, self.handle_quit)
        signal.signal(signal.SIGTERM, self.handle_exit)
        signal.signal(signal.SIGINT, self.handle_quit)
        signal.signal(signal.SIGWINCH, self.handle_winch)
        signal.signal(signal.SIGUSR1, self.handle_usr1)
        signal.signal(signal.SIGABRT, self.handle_abort)

        # Don't let SIGTERM and SIGUSR1 disturb active requests
        # by interrupting system calls
        if hasattr(signal, 'siginterrupt'):  # python >= 2.6
            signal.siginterrupt(signal.SIGTERM, False)
            signal.siginterrupt(signal.SIGUSR1, False) 
Example 10
Project: Flask-P2P   Author: chalasr   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)
        """
        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 11
Project: pwnableweb   Author: Matir   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def _start_internal(self):
    self._started = True
    # Signals
    for sig in (signal.SIGINT, signal.SIGQUIT, signal.SIGTERM):
      signal.signal(sig, self.stop)

    # Setup the browser & xvfb
    self.xvfb = xvfbwrapper.Xvfb(width=1024, height=768)
    self.xvfb.start()
    self.browser = webdriver.Chrome(executable_path=self._chromedriver_path)
    self._run_event.set()
    self._stop_event.clear()


    self._thread = threading.Thread(target=self._wrap_run)
    self._thread.start()
    try:
      while True:
        time.sleep(self._interval)
        self._run_event.set()
    except KeyboardInterrupt:
      print 'Saw CTRL-C, shutting down.'
      self.stop() 
Example 12
Project: sagemaker-containers   Author: aws   File: _server.py    License: Apache License 2.0 6 votes vote down vote up
def _add_sigterm_handler(nginx, gunicorn):
    """Placeholder docstring"""

    def _terminate(signo, frame):  # pylint: disable=unused-argument
        if nginx:
            try:
                os.kill(nginx.pid, signal.SIGQUIT)
            except OSError:
                pass

        try:
            os.kill(gunicorn.pid, signal.SIGTERM)
        except OSError:
            pass

    signal.signal(signal.SIGTERM, _terminate) 
Example 13
Project: mayhem   Author: econchick   File: mayhem_4.py    License: MIT License 6 votes vote down vote up
def main():
    executor = concurrent.futures.ThreadPoolExecutor()
    loop = asyncio.get_event_loop()
    signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT, signal.SIGQUIT)
    for s in signals:
        loop.add_signal_handler(
            s, lambda s=s: asyncio.create_task(shutdown(loop, executor, signal=s)))
    q = queue.Queue()

    try:
        loop.create_task(publish(executor, q))
        loop.create_task(consume(executor, q))
        loop.run_forever()
    finally:
        loop.close()
        logging.info("Successfully shutdown the Mayhem service.") 
Example 14
Project: mayhem   Author: econchick   File: mayhem_5.py    License: MIT License 6 votes vote down vote up
def main():
    executor = concurrent.futures.ThreadPoolExecutor()
    loop = asyncio.get_event_loop()
    signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT, signal.SIGQUIT)
    for s in signals:
        loop.add_signal_handler(
            s, lambda s=s: asyncio.create_task(shutdown(loop, executor, signal=s)))
    q = queue.Queue()

    try:
        loop.create_task(publish(executor, q))
        loop.create_task(consume(executor, q))
        loop.run_forever()
    finally:
        loop.close()
        logging.info("Successfully shutdown the Mayhem service.") 
Example 15
Project: mayhem   Author: econchick   File: mayhem_3.py    License: MIT License 6 votes vote down vote up
def main():
    executor = concurrent.futures.ThreadPoolExecutor()
    loop = asyncio.get_event_loop()
    signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT, signal.SIGQUIT)
    for s in signals:
        loop.add_signal_handler(
            s, lambda s=s: asyncio.create_task(shutdown(loop, signal=s)))
    q = queue.Queue()

    try:
        loop.create_task(publish(executor, q))
        loop.create_task(consume(executor, q))
        loop.run_forever()
    finally:
        loop.close()
        logging.info("Successfully shutdown the Mayhem service.") 
Example 16
Project: mayhem   Author: econchick   File: mayhem_8.py    License: MIT License 6 votes vote down vote up
def main():
    executor = concurrent.futures.ThreadPoolExecutor()
    loop = asyncio.get_event_loop()
    signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT, signal.SIGQUIT)
    for s in signals:
        loop.add_signal_handler(
            s, lambda s=s: asyncio.create_task(shutdown(loop, executor, signal=s)))
    handle_exc_func = functools.partial(handle_exception, executor)
    loop.set_exception_handler(handle_exc_func)
    q = queue.Queue()

    try:
        loop.create_task(publish(executor, q))
        loop.create_task(consume(executor, q))
        loop.run_forever()
    finally:
        loop.close()
        logging.info("Successfully shutdown the Mayhem service.") 
Example 17
Project: mayhem   Author: econchick   File: mayhem_6.py    License: MIT License 6 votes vote down vote up
def main():
    executor = concurrent.futures.ThreadPoolExecutor()
    loop = asyncio.get_event_loop()
    signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT, signal.SIGQUIT)
    for s in signals:
        loop.add_signal_handler(
            s, lambda s=s: asyncio.create_task(shutdown(loop, executor, signal=s)))
    handle_exc_func = functools.partial(handle_exception, executor)
    loop.set_exception_handler(handle_exc_func)
    q = queue.Queue()

    try:
        loop.create_task(publish(executor, q))
        loop.create_task(consume(executor, q))
        loop.run_forever()
    finally:
        loop.close()
        logging.info("Successfully shutdown the Mayhem service.") 
Example 18
Project: mayhem   Author: econchick   File: mayhem_9.py    License: MIT License 6 votes vote down vote up
def main():
    executor = concurrent.futures.ThreadPoolExecutor()
    loop = asyncio.get_event_loop()
    signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT, signal.SIGQUIT)
    for s in signals:
        loop.add_signal_handler(
            s, lambda s=s: asyncio.create_task(shutdown(loop, executor, signal=s)))
    handle_exc_func = functools.partial(handle_exception, executor)
    loop.set_exception_handler(handle_exc_func)
    q = queue.Queue()

    try:
        loop.create_task(publish(executor, q))
        loop.create_task(consume(executor, q))
        loop.run_forever()
    finally:
        loop.close()
        logging.info("Successfully shutdown the Mayhem service.") 
Example 19
Project: pilot   Author: PanDAWMS   File: RunJobEdison.py    License: Apache License 2.0 6 votes vote down vote up
def sig2exc(sig, frm):
            """ signal handler """

            error = PilotErrors()
            runJob.setGlobalPilotErrorDiag("!!FAILED!!3000!! SIGTERM Signal %s is caught in child pid=%d!\n" % (sig, os.getpid()))
            tolog(runJob.getGlobalPilotErrorDiag())
            if sig == signal.SIGTERM:
                runJob.setGlobalErrorCode(error.ERR_SIGTERM)
            elif sig == signal.SIGQUIT:
                runJob.setGlobalErrorCode(error.ERR_SIGQUIT)
            elif sig == signal.SIGSEGV:
                runJob.setGlobalErrorCode(error.ERR_SIGSEGV)
            elif sig == signal.SIGXCPU:
                runJob.setGlobalErrorCode(error.ERR_SIGXCPU)
            elif sig == signal.SIGBUS:
                runJob.setGlobalErrorCode(error.ERR_SIGBUS)
            elif sig == signal.SIGUSR1:
                runJob.setGlobalErrorCode(error.ERR_SIGUSR1)
            else:
                runJob.setGlobalErrorCode(error.ERR_KILLSIGNAL)
            runJob.setFailureCode(runJob.getGlobalErrorCode)
            # print to stderr
            print >> sys.stderr, runJob.getGlobalPilotErrorDiag()
            raise SystemError(sig) 
Example 20
Project: pilot   Author: PanDAWMS   File: RunJobArgo.py    License: Apache License 2.0 6 votes vote down vote up
def sig2exc(sig, frm):
            """ signal handler """

            error = PilotErrors()
            runJob.setGlobalPilotErrorDiag("!!FAILED!!3000!! SIGTERM Signal %s is caught in child pid=%d!\n" % (sig, os.getpid()))
            tolog(runJob.getGlobalPilotErrorDiag())
            if sig == signal.SIGTERM:
                runJob.setGlobalErrorCode(error.ERR_SIGTERM)
            elif sig == signal.SIGQUIT:
                runJob.setGlobalErrorCode(error.ERR_SIGQUIT)
            elif sig == signal.SIGSEGV:
                runJob.setGlobalErrorCode(error.ERR_SIGSEGV)
            elif sig == signal.SIGXCPU:
                runJob.setGlobalErrorCode(error.ERR_SIGXCPU)
            elif sig == signal.SIGBUS:
                runJob.setGlobalErrorCode(error.ERR_SIGBUS)
            elif sig == signal.SIGUSR1:
                runJob.setGlobalErrorCode(error.ERR_SIGUSR1)
            else:
                runJob.setGlobalErrorCode(error.ERR_KILLSIGNAL)
            runJob.setFailureCode(runJob.getGlobalErrorCode)
            # print to stderr
            print >> sys.stderr, runJob.getGlobalPilotErrorDiag()
            raise SystemError(sig) 
Example 21
Project: pilot   Author: PanDAWMS   File: RunJob.py    License: Apache License 2.0 6 votes vote down vote up
def sig2exc(sig, frm):
            """ signal handler """

            error = PilotErrors()
            runJob.setGlobalPilotErrorDiag("!!FAILED!!3000!! SIGTERM Signal %s is caught in child pid=%d!\n" % (sig, os.getpid()))
            tolog(runJob.getGlobalPilotErrorDiag())
            if sig == signal.SIGTERM:
                runJob.setGlobalErrorCode(error.ERR_SIGTERM)
            elif sig == signal.SIGQUIT:
                runJob.setGlobalErrorCode(error.ERR_SIGQUIT)
            elif sig == signal.SIGSEGV:
                runJob.setGlobalErrorCode(error.ERR_SIGSEGV)
            elif sig == signal.SIGXCPU:
                runJob.setGlobalErrorCode(error.ERR_SIGXCPU)
            elif sig == signal.SIGBUS:
                runJob.setGlobalErrorCode(error.ERR_SIGBUS)
            elif sig == signal.SIGUSR1:
                runJob.setGlobalErrorCode(error.ERR_SIGUSR1)
            else:
                runJob.setGlobalErrorCode(error.ERR_KILLSIGNAL)
            runJob.setFailureCode(runJob.getGlobalErrorCode())
            # print to stderr
            print >> sys.stderr, runJob.getGlobalPilotErrorDiag()
            raise SystemError(sig) 
Example 22
Project: pilot   Author: PanDAWMS   File: RunJobAnselm.py    License: Apache License 2.0 6 votes vote down vote up
def sig2exc(sig, frm):
            """ signal handler """

            error = PilotErrors()
            runJob.setGlobalPilotErrorDiag("!!FAILED!!3000!! SIGTERM Signal %s is caught in child pid=%d!\n" % (sig, os.getpid()))
            tolog(runJob.getGlobalPilotErrorDiag())
            if sig == signal.SIGTERM:
                runJob.setGlobalErrorCode(error.ERR_SIGTERM)
            elif sig == signal.SIGQUIT:
                runJob.setGlobalErrorCode(error.ERR_SIGQUIT)
            elif sig == signal.SIGSEGV:
                runJob.setGlobalErrorCode(error.ERR_SIGSEGV)
            elif sig == signal.SIGXCPU:
                runJob.setGlobalErrorCode(error.ERR_SIGXCPU)
            elif sig == signal.SIGBUS:
                runJob.setGlobalErrorCode(error.ERR_SIGBUS)
            elif sig == signal.SIGUSR1:
                runJob.setGlobalErrorCode(error.ERR_SIGUSR1)
            else:
                runJob.setGlobalErrorCode(error.ERR_KILLSIGNAL)
            runJob.setFailureCode(runJob.getGlobalErrorCode)
            # print to stderr
            print >> sys.stderr, runJob.getGlobalPilotErrorDiag()
            raise SystemError(sig) 
Example 23
Project: pilot   Author: PanDAWMS   File: RunJobTitan.py    License: Apache License 2.0 6 votes vote down vote up
def sig2exc(sig, frm):
            """ signal handler """

            error = PilotErrors()
            runJob.setGlobalPilotErrorDiag("!!FAILED!!3000!! SIGTERM Signal %s is caught in child pid=%d!\n" % (sig, os.getpid()))
            tolog(runJob.getGlobalPilotErrorDiag())
            if sig == signal.SIGTERM:
                runJob.setGlobalErrorCode(error.ERR_SIGTERM)
            elif sig == signal.SIGQUIT:
                runJob.setGlobalErrorCode(error.ERR_SIGQUIT)
            elif sig == signal.SIGSEGV:
                runJob.setGlobalErrorCode(error.ERR_SIGSEGV)
            elif sig == signal.SIGXCPU:
                runJob.setGlobalErrorCode(error.ERR_SIGXCPU)
            elif sig == signal.SIGBUS:
                runJob.setGlobalErrorCode(error.ERR_SIGBUS)
            elif sig == signal.SIGUSR1:
                runJob.setGlobalErrorCode(error.ERR_SIGUSR1)
            else:
                runJob.setGlobalErrorCode(error.ERR_KILLSIGNAL)
            runJob.setFailureCode(runJob.getGlobalErrorCode)
            # print to stderr
            print >> sys.stderr, runJob.getGlobalPilotErrorDiag()
            raise SystemError(sig) 
Example 24
Project: pilot   Author: PanDAWMS   File: RunJobHopper.py    License: Apache License 2.0 6 votes vote down vote up
def sig2exc(sig, frm):
            """ signal handler """

            error = PilotErrors()
            runJob.setGlobalPilotErrorDiag("!!FAILED!!3000!! SIGTERM Signal %s is caught in child pid=%d!\n" % (sig, os.getpid()))
            tolog(runJob.getGlobalPilotErrorDiag())
            if sig == signal.SIGTERM:
                runJob.setGlobalErrorCode(error.ERR_SIGTERM)
            elif sig == signal.SIGQUIT:
                runJob.setGlobalErrorCode(error.ERR_SIGQUIT)
            elif sig == signal.SIGSEGV:
                runJob.setGlobalErrorCode(error.ERR_SIGSEGV)
            elif sig == signal.SIGXCPU:
                runJob.setGlobalErrorCode(error.ERR_SIGXCPU)
            elif sig == signal.SIGBUS:
                runJob.setGlobalErrorCode(error.ERR_SIGBUS)
            elif sig == signal.SIGUSR1:
                runJob.setGlobalErrorCode(error.ERR_SIGUSR1)
            else:
                runJob.setGlobalErrorCode(error.ERR_KILLSIGNAL)
            runJob.setFailureCode(runJob.getGlobalErrorCode)
            # print to stderr
            print >> sys.stderr, runJob.getGlobalPilotErrorDiag()
            raise SystemError(sig) 
Example 25
Project: simpleflow   Author: botify-labs   File: test_heartbeat.py    License: MIT License 6 votes vote down vote up
def test_heartbeat_process_kill_parent(self):
        heartbeat = FakeHeartbeat(1000)
        heartbeater = HeartbeatProcess(heartbeat, interval=0.1)

        token = uuid4()
        task = FakeTask('test_task')

        result_queue = mp.Queue()
        handler = FakeTaskHandler(heartbeater.run,
                                  (token, task),
                                  {},
                                  result_queue)
        handler_process = mp.Process(target=handler)

        handler_process.start()
        time.sleep(2)
        heartbeat_pid = result_queue.get()
        handler_process.terminate()
        os.kill(handler_process.pid, signal.SIGQUIT)
        handler_process.join()
        time.sleep(2)
        with self.assertRaises(OSError):
            os.kill(heartbeat_pid, signal.SIGKILL) 
Example 26
Project: RPiNWR   Author: ke4roh   File: AIWIBoardContext.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __enter__(self):
        # Make sure to cleanup GPIO afterward
        if not self.__signals_trapped:
            self.__signals_trapped = True
            for sig in [signal.SIGQUIT, signal.SIGTERM, signal.SIGTSTP]:
                if hasattr(signal.getsignal(sig), '__call__'):
                    deleg = signal.getsignal(sig)

                    def delegate(signum, stack):
                        self.__exit__(None, None, None)
                        deleg(signum, stack)

                    signal.signal(sig, delegate)
                else:
                    def delegate(signum, stack):
                        self.__exit__(None, None, None)

                    signal.signal(sig, delegate)
        return self 
Example 27
Project: pglookout   Author: aiven   File: conftest.py    License: Apache License 2.0 6 votes vote down vote up
def kill(self, force=True, immediate=True):
        if self.pg is None:
            return
        if force:
            os.kill(self.pg.pid, signal.SIGKILL)
        elif immediate:
            os.kill(self.pg.pid, signal.SIGQUIT)
        else:
            os.kill(self.pg.pid, signal.SIGTERM)
        timeout = time.monotonic() + 10
        while (self.pg.poll() is None) and (time.monotonic() < timeout):
            time.sleep(0.1)
        if not force and self.pg.poll() is None:
            raise Exception("PG pid {} not dead".format(self.pg.pid))


# NOTE: cannot use 'tmpdir' fixture here, it only works in 'function' scope 
Example 28
Project: sanic   Author: huge-success   File: worker.py    License: MIT License 5 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 29
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 _shutdown(self):
        """Shutdown all slaves."""
        for ssh_proc in self._ssh_procs:
            os.kill(ssh_proc.pid, signal.SIGQUIT)
        super(NetworkPPScheduler, self)._shutdown()
        if self.verbose:
            print "All slaves shut down." 
Example 30
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."