Python signal.SIGHUP Examples

The following are 30 code examples for showing how to use signal.SIGHUP(). 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: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_SIGHUP_tty(self):
        # When not daemonized, SIGHUP should shut down the server.
        try:
            from signal import SIGHUP
        except ImportError:
            return self.skip('skipped (no SIGHUP) ')

        # Spawn the process.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'))
        p.write_conf(
            extra='test_case_name: "test_SIGHUP_tty"')
        p.start(imports='cherrypy.test._test_states_demo')
        # Send a SIGHUP
        os.kill(p.get_pid(), SIGHUP)
        # This might hang if things aren't working right, but meh.
        p.join() 
Example 2
Project: dataflow   Author: tensorpack   File: concurrency.py    License: Apache License 2.0 6 votes vote down vote up
def enable_death_signal(_warn=True):
    """
    Set the "death signal" of the current process, so that
    the current process will be cleaned with guarantee
    in case the parent dies accidentally.
    """
    if platform.system() != 'Linux':
        return
    try:
        import prctl    # pip install python-prctl
    except ImportError:
        if _warn:
            log_once('"import prctl" failed! Install python-prctl so that processes can be cleaned with guarantee.',
                     'warn')
        return
    else:
        assert hasattr(prctl, 'set_pdeathsig'), \
            "prctl.set_pdeathsig does not exist! Note that you need to install 'python-prctl' instead of 'prctl'."
        # is SIGHUP a good choice?
        prctl.set_pdeathsig(signal.SIGHUP) 
Example 3
Project: networking-sfc   Author: openstack   File: test_service.py    License: Apache License 2.0 6 votes vote down vote up
def _test_restart_service_on_sighup(self, service, workers=1):
        self._start_server(callback=service, workers=workers)
        os.kill(self.service_pid, signal.SIGHUP)
        expected_msg = (
            test_server.FAKE_START_MSG * workers +
            test_server.FAKE_RESET_MSG * (workers + 1))
        expected_size = len(expected_msg)

        utils.wait_until_true(
            lambda: (os.path.isfile(self.temp_file) and
                     os.stat(self.temp_file).st_size ==
                     expected_size),
            timeout=5, sleep=0.1,
            exception=RuntimeError(
                "Timed out waiting for file %(filename)s to be created and "
                "its size become equal to %(size)s." %
                {'filename': self.temp_file,
                 'size': expected_size}))
        with open(self.temp_file, 'rb') as f:
            res = f.readline()
            self.assertEqual(expected_msg, res) 
Example 4
Project: covimerage   Author: Vimjas   File: test_cli.py    License: MIT License 6 votes vote down vote up
def test_run_forwards_sighup(devnull):
    proc = subprocess.Popen([
            sys.executable, '-m', 'covimerage', 'run',
            '--no-write-data', '--no-wrap-profile',
            '--profile-file', devnull.name,
            sys.executable, '-c',
            'import signal, sys, time; '
            'signal.signal(signal.SIGHUP, lambda *args: sys.exit(89)); '
            'time.sleep(2)'],
                          stderr=subprocess.PIPE)
    time.sleep(1)
    proc.send_signal(signal.SIGHUP)
    _, stderr = proc.communicate()
    exit_code = proc.returncode

    stderr = stderr.decode()
    assert 'Command exited non-zero: 89' in stderr
    assert exit_code == 89 
Example 5
Project: ACE   Author: IntegralDefense   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def initialize_signal_handlers(self):
        def handle_sighup(signum, frame):
            logging.info("received SIGHUP")
            self.sighup_received = True

        def handle_sigterm(signal, frame):
            logging.info("received SIGTERM")
            self.sigterm_received = True

        def handle_sigint(signal, frame):
            logging.info("received SIGINT")
            self.sigint_received = True

        signal.signal(signal.SIGTERM, handle_sigterm)
        signal.signal(signal.SIGHUP, handle_sighup)
        signal.signal(signal.SIGINT, handle_sigint) 
Example 6
Project: octavia   Author: openstack   File: health_manager.py    License: Apache License 2.0 6 votes vote down vote up
def hm_health_check(exit_event):
    hm = health_manager.HealthManager(exit_event)
    signal.signal(signal.SIGHUP, _mutate_config)

    @periodics.periodic(CONF.health_manager.health_check_interval,
                        run_immediately=True)
    def periodic_health_check():
        hm.health_check()

    health_check = periodics.PeriodicWorker(
        [(periodic_health_check, None, None)],
        schedule_strategy='aligned_last_finished')

    def hm_exit(*args, **kwargs):
        health_check.stop()
        hm.executor.shutdown()
    signal.signal(signal.SIGINT, hm_exit)
    LOG.debug("Pausing before starting health check")
    exit_event.wait(CONF.health_manager.heartbeat_timeout)
    health_check.start() 
Example 7
Project: octavia   Author: openstack   File: driver_agent.py    License: Apache License 2.0 6 votes vote down vote up
def _process_wrapper(exit_event, proc_name, function, agent_name=None):
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    signal.signal(signal.SIGHUP, _mutate_config)
    if agent_name:
        process_title = 'octavia-driver-agent - {} -- {}'.format(
            proc_name, agent_name)
    else:
        process_title = 'octavia-driver-agent - {}'.format(proc_name)
    setproctitle.setproctitle(process_title)
    while not exit_event.is_set():
        try:
            function(exit_event)
        except Exception as e:
            if agent_name:
                LOG.exception('Provider agent "%s" raised exception: %s. '
                              'Restarting the "%s" provider agent.',
                              agent_name, str(e), agent_name)
            else:
                LOG.exception('%s raised exception: %s. '
                              'Restarting %s.',
                              proc_name, str(e), proc_name)
            time.sleep(1)
            continue
        break 
Example 8
Project: Computable   Author: ktraunmueller   File: _pexpect.py    License: MIT License 6 votes vote down vote up
def close (self, force=True):   # File-like object.

        """This closes the connection with the child application. Note that
        calling close() more than once is valid. This emulates standard Python
        behavior with files. Set force to True if you want to make sure that
        the child is terminated (SIGKILL is sent if the child ignores SIGHUP
        and SIGINT). """

        if not self.closed:
            self.flush()
            os.close (self.child_fd)
            time.sleep(self.delayafterclose) # Give kernel time to update process status.
            if self.isalive():
                if not self.terminate(force):
                    raise ExceptionPexpect ('close() could not terminate the child using terminate()')
            self.child_fd = -1
            self.closed = True
            #self.pid = None 
Example 9
Project: cotyledon   Author: sileht   File: test_functional.py    License: Apache License 2.0 6 votes vote down vote up
def test_sighup(self):
        self.assert_everything_has_started()
        os.kill(self.subp.pid, signal.SIGHUP)
        time.sleep(0.5)
        lines = sorted(self.get_lines(6))
        lines = self.hide_pids(lines)
        self.assertEqual([
            b'DEBUG:cotyledon._service:Run service light(0) [XXXX]',
            b'ERROR:cotyledon.tests.examples:heavy reload',
            b'ERROR:cotyledon.tests.examples:heavy reload',
            b'ERROR:cotyledon.tests.examples:master reload hook',
            b'INFO:cotyledon._service:Caught SIGTERM signal, '
            b'graceful exiting of service light(0) [XXXX]',
            b'INFO:cotyledon._service_manager:Child XXXX exited with status 0'
        ], lines)

        os.kill(self.subp.pid, signal.SIGINT)
        time.sleep(0.5)
        self.assert_everything_is_dead(1) 
Example 10
Project: cotyledon   Author: sileht   File: _utils.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self):
        # Setup signal fd, this allows signal to behave correctly
        if os.name == 'posix':
            self.signal_pipe_r, self.signal_pipe_w = os.pipe()
            self._set_nonblock(self.signal_pipe_r)
            self._set_nonblock(self.signal_pipe_w)
            signal.set_wakeup_fd(self.signal_pipe_w)

        self._signals_received = collections.deque()

        signal.signal(signal.SIGINT, signal.SIG_DFL)
        if os.name == 'posix':
            signal.signal(signal.SIGCHLD, signal.SIG_DFL)
            signal.signal(signal.SIGTERM, self._signal_catcher)
            signal.signal(signal.SIGALRM, self._signal_catcher)
            signal.signal(signal.SIGHUP, self._signal_catcher)
        else:
            # currently a noop on window...
            signal.signal(signal.SIGTERM, self._signal_catcher)
            # FIXME(sileht): should allow to catch signal CTRL_BREAK_EVENT,
            # but we to create the child process with CREATE_NEW_PROCESS_GROUP
            # to make this work, so current this is a noop for later fix
            signal.signal(signal.SIGBREAK, self._signal_catcher) 
Example 11
Project: pipenv   Author: pypa   File: ptyprocess.py    License: MIT License 6 votes vote down vote up
def close(self, force=True):
        '''This closes the connection with the child application. Note that
        calling close() more than once is valid. This emulates standard Python
        behavior with files. Set force to True if you want to make sure that
        the child is terminated (SIGKILL is sent if the child ignores SIGHUP
        and SIGINT). '''
        if not self.closed:
            self.flush()
            self.fileobj.close() # Closes the file descriptor
            # Give kernel time to update process status.
            time.sleep(self.delayafterclose)
            if self.isalive():
                if not self.terminate(force):
                    raise PtyProcessError('Could not terminate the child.')
            self.fd = -1
            self.closed = True
            #self.pid = None 
Example 12
Project: pycepa   Author: pycepa   File: daemon.py    License: GNU General Public License v3.0 6 votes vote down vote up
def reload():
    """
    Sends a SIGHUP to the running daemon to tell it to reload all modules.
    """
    log.info('reloading server.')

    try:
        pid = read_pid()
    except Exception as e:
        log.critical('could not read PID file: %s' % e)
        return

    try:
        os.kill(pid, signal.SIGHUP)
    except Exception as e:
        log.critical('could not reload server: %s' % e) 
Example 13
Project: smod-1   Author: theralfbrown   File: pexpect.py    License: GNU General Public License v2.0 6 votes vote down vote up
def close (self, force=True):   # File-like object.

        """This closes the connection with the child application. Note that
        calling close() more than once is valid. This emulates standard Python
        behavior with files. Set force to True if you want to make sure that
        the child is terminated (SIGKILL is sent if the child ignores SIGHUP
        and SIGINT). """

        if not self.closed:
            self.flush()
            os.close (self.child_fd)
            time.sleep(self.delayafterclose) # Give kernel time to update process status.
            if self.isalive():
                if not self.terminate(force):
                    raise ExceptionPexpect ('close() could not terminate the child using terminate()')
            self.child_fd = -1
            self.closed = True
            #self.pid = None 
Example 14
Project: sublime_debugger   Author: daveleroy   File: ptyprocess.py    License: MIT License 6 votes vote down vote up
def close(self, force=True):
        '''This closes the connection with the child application. Note that
        calling close() more than once is valid. This emulates standard Python
        behavior with files. Set force to True if you want to make sure that
        the child is terminated (SIGKILL is sent if the child ignores SIGHUP
        and SIGINT). '''
        if not self.closed:
            self.flush()
            self.fileobj.close() # Closes the file descriptor
            # Give kernel time to update process status.
            time.sleep(self.delayafterclose)
            if self.isalive():
                if not self.terminate(force):
                    raise PtyProcessError('Could not terminate the child.')
            self.fd = -1
            self.closed = True
            #self.pid = None 
Example 15
Project: RAFCON   Author: DLR-RM   File: start.py    License: Eclipse Public License 1.0 6 votes vote down vote up
def register_signal_handlers(callback):
    # When using plain signal.signal to install a signal handler, the GUI will not shutdown until it receives the
    # focus again. The following logic (inspired from https://stackoverflow.com/a/26457317) fixes this
    def install_glib_handler(sig):
        unix_signal_add = None

        if hasattr(GLib, "unix_signal_add"):
            unix_signal_add = GLib.unix_signal_add
        elif hasattr(GLib, "unix_signal_add_full"):
            unix_signal_add = GLib.unix_signal_add_full

        if unix_signal_add:
            unix_signal_add(GLib.PRIORITY_HIGH, sig, callback, sig)

    def idle_handler(*args):
        GLib.idle_add(callback, *args, priority=GLib.PRIORITY_HIGH)

    for signal_code in [signal.SIGHUP, signal.SIGINT, signal.SIGTERM]:
        signal.signal(signal_code, idle_handler)
        GLib.idle_add(install_glib_handler, signal_code, priority=GLib.PRIORITY_HIGH) 
Example 16
Project: Fluid-Designer   Author: Microvellum   File: test_subprocess.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_send_signal(self):
        code = 'import time; print("sleeping", flush=True); time.sleep(3600)'
        args = [sys.executable, '-c', code]
        create = asyncio.create_subprocess_exec(*args,
                                                stdout=subprocess.PIPE,
                                                loop=self.loop)
        proc = self.loop.run_until_complete(create)

        @asyncio.coroutine
        def send_signal(proc):
            # basic synchronization to wait until the program is sleeping
            line = yield from proc.stdout.readline()
            self.assertEqual(line, b'sleeping\n')

            proc.send_signal(signal.SIGHUP)
            returncode = (yield from proc.wait())
            return returncode

        returncode = self.loop.run_until_complete(send_signal(proc))
        self.assertEqual(-signal.SIGHUP, returncode) 
Example 17
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 18
Project: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_SIGHUP_daemonized(self):
        # When daemonized, SIGHUP should restart the server.
        try:
            from signal import SIGHUP
        except ImportError:
            return self.skip('skipped (no SIGHUP) ')

        if os.name not in ['posix']:
            return self.skip('skipped (not on posix) ')

        # Spawn the process and wait, when this returns, the original process
        # is finished.  If it daemonized properly, we should still be able
        # to access pages.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'),
                             wait=True, daemonize=True)
        p.write_conf(
            extra='test_case_name: "test_SIGHUP_daemonized"')
        p.start(imports='cherrypy.test._test_states_demo')

        pid = p.get_pid()
        try:
            # Send a SIGHUP
            os.kill(pid, SIGHUP)
            # Give the server some time to restart
            time.sleep(2)
            self.getPage('/pid')
            self.assertStatus(200)
            new_pid = int(self.body)
            self.assertNotEqual(new_pid, pid)
        finally:
            # Shut down the spawned process
            self.getPage('/exit')
        p.join() 
Example 19
Project: Zopkio   Author: linkedin   File: deployer.py    License: Apache License 2.0 5 votes vote down vote up
def hangup(self, unique_id, configs=None):
    """
    Issue a signal to hangup the specified process

    :Parameter unique_id: the name of the process
    """
    self._send_signal(unique_id, signal.SIGHUP, configs) 
Example 20
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 21
Project: python-slackclient   Author: slackapi   File: client.py    License: MIT License 5 votes vote down vote up
def start(self) -> asyncio.Future:
        """Starts an RTM Session with Slack.

        Makes an authenticated call to Slack's RTM API to retrieve
        a websocket URL and then connects to the message server.
        As events stream-in we run any associated callbacks stored
        on the client.

        If 'auto_reconnect' is specified we
        retrieve a new url and reconnect any time the connection
        is lost unintentionally or an exception is thrown.

        Raises:
            SlackApiError: Unable to retrieve RTM URL from Slack.
        """
        # TODO: Add Windows support for graceful shutdowns.
        if os.name != "nt" and current_thread() == main_thread():
            signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
            for s in signals:
                self._event_loop.add_signal_handler(s, self.stop)

        future = asyncio.ensure_future(self._connect_and_read(), loop=self._event_loop)

        if self.run_async:
            return future
        return self._event_loop.run_until_complete(future) 
Example 22
Project: NINJA-PingU   Author: OWASP   File: terminal.py    License: GNU General Public License v3.0 5 votes vote down vote up
def close(self):
        """Close ourselves"""
        dbg('close: called')
        self.cnxids.remove_signal(self.vte, 'child-exited')
        self.emit('close-term')
        try:
            dbg('close: killing %d' % self.pid)
            os.kill(self.pid, signal.SIGHUP)
        except Exception, ex:
            # We really don't want to care if this failed. Deep OS voodoo is
            # not what we should be doing.
            dbg('os.kill failed: %s' % ex)
            pass 
Example 23
Project: ACE   Author: IntegralDefense   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def wait(self):
        """Waits for the engine to stop."""
        if self.single_threaded_mode:
            return

        self.initialize_signal_handlers()
        logging.info("waiting for engine process {} to complete".format(self.engine_process.pid))

        while True:
            try:
                self.engine_process.join(0.1)
                if not self.engine_process.is_alive():
                    logging.debug("detected end of process {}".format(self.engine_process.pid))
                    break

                if self.sigterm_received:
                    try:
                        logging.info("sending SIGTERM to {}".format(self.engine_process.pid))
                        os.kill(self.engine_process.pid, signal.SIGTERM)
                    except Exception as e:
                        logging.error("unable to send SIGTERM to {}: {}".format(self.engine_process.pid, e))
                    finally:
                        self.sigterm_received = False

                if self.sighup_received:
                    try:
                        logging.info("sending SIGHUP to {}".format(self.engine_process.pid))
                        os.kill(self.engine_process.pid, signal.SIGHUP)
                    except Exception as e:
                        logging.error("unable to send SIGHUP to {}: {}".format(self.engine_process.pid, e))
                    finally:
                        self.sighup_received = False

            except Exception as e:
                logging.error("unable to join engine process {}".format(e)) 
Example 24
Project: ACE   Author: IntegralDefense   File: test.py    License: Apache License 2.0 5 votes vote down vote up
def test_unix_signals(self):
        engine = TestEngine()
        engine.start()

        # tell ACE to reload the configuration and then reload all the workers
        os.kill(engine.engine_process.pid, signal.SIGHUP)

        wait_for_log_count('reloading engine configuration', 1, 5)
        wait_for_log_count('got command to restart workers', 1, 5)
        wait_for_log_count('started worker loop', 2)
        engine.controlled_stop()
        engine.wait() 
Example 25
Project: borgmatic   Author: witten   File: signals.py    License: GNU General Public License v3.0 5 votes vote down vote up
def configure_signals():  # pragma: no cover
    '''
    Configure borgmatic's signal handlers to pass relevant signals through to any child processes
    like Borg. Note that SIGINT gets passed through even without these changes.
    '''
    for signal_number in (signal.SIGHUP, signal.SIGTERM, signal.SIGUSR1, signal.SIGUSR2):
        signal.signal(signal_number, _handle_signal) 
Example 26
Project: minemeld-core   Author: PaloAltoNetworks   File: supervisorapi.py    License: Apache License 2.0 5 votes vote down vote up
def hup_minemeld_web():
    info = MMSupervisor.supervisor.getProcessInfo('minemeld-web')

    apipid = info['pid']
    os.kill(apipid, SIGHUP)

    return jsonify(result='OK') 
Example 27
Project: minemeld-core   Author: PaloAltoNetworks   File: restore.py    License: Apache License 2.0 5 votes vote down vote up
def _reload_candidate_config(supervisor_url):
    SR = redis.StrictRedis()
    ckeys = SR.keys('{}*'.format(REDIS_KEY_PREFIX))
    if ckeys:
        for ck in ckeys:
            LOG.info('Deleting {}'.format(ck))
            SR.delete(ck)

    LOG.info('Candidate config keys deleted')

    sserver = xmlrpclib.ServerProxy(
        'http://127.0.0.1',
        transport=supervisor.xmlrpc.SupervisorTransport(
            None,
            None,
            supervisor_url
        )
    )

    # check supervisor state
    sstate = sserver.supervisor.getState()
    if sstate['statecode'] == 2:  # FATAL
        raise RuntimeError('Supervisor state: 2')

    if sstate['statecode'] != 1:
        raise RuntimeError(
            "Supervisor transitioning to a new state, restore not performed"
        )

    # check minemeld-engine state
    pinfo = sserver.supervisor.getProcessInfo('minemeld-web')
    if pinfo['statename'] != 'RUNNING':
        raise RuntimeError('minemeld-web not running, reload not sent')

    os.kill(pinfo['pid'], signal.SIGHUP)

    LOG.info('API process reloaded') 
Example 28
Project: octavia   Author: openstack   File: test_driver_agent.py    License: Apache License 2.0 5 votes vote down vote up
def test_handle_mutate_config(self, mock_conf, mock_os_kill):
        driver_agent._handle_mutate_config(1, 2)
        mock_conf.mutate_config_files.assert_called_once()
        os_calls = [mock.call(1, signal.SIGHUP), mock.call(2, signal.SIGHUP)]
        mock_os_kill.assert_has_calls(os_calls, any_order=True) 
Example 29
Project: octavia   Author: openstack   File: test_health_manager.py    License: Apache License 2.0 5 votes vote down vote up
def test_handle_mutate_config(self, mock_mutate, mock_kill):
        health_manager._handle_mutate_config(1, 2)

        mock_mutate.assert_called_once()

        calls = [mock.call(1, signal.SIGHUP), mock.call(2, signal.SIGHUP)]
        mock_kill.assert_has_calls(calls) 
Example 30
Project: octavia   Author: openstack   File: health_manager.py    License: Apache License 2.0 5 votes vote down vote up
def hm_listener(exit_event):
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    signal.signal(signal.SIGHUP, _mutate_config)
    udp_getter = heartbeat_udp.UDPStatusGetter()
    while not exit_event.is_set():
        try:
            udp_getter.check()
        except Exception as e:
            LOG.error('Health Manager listener experienced unknown error: %s',
                      e)
    LOG.info('Waiting for executor to shutdown...')
    udp_getter.health_executor.shutdown()
    udp_getter.stats_executor.shutdown()
    LOG.info('Executor shutdown finished.')