Python signal.SIGHUP Examples

The following are 30 code examples of signal.SIGHUP(). 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: _utils.py    From cotyledon with Apache License 2.0 7 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 #2
Source File: ptyprocess.py    From pipenv with 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 #3
Source File: __init__.py    From ACE with 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 #4
Source File: test_cli.py    From covimerage with 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
Source File: concurrency.py    From dataflow with 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 #6
Source File: sig.py    From naz with 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 #7
Source File: test_service.py    From networking-sfc with 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 #8
Source File: test_states.py    From cherrypy with 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 #9
Source File: test_subprocess.py    From Fluid-Designer with 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 #10
Source File: health_manager.py    From octavia with 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 #11
Source File: start.py    From RAFCON with 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 #12
Source File: driver_agent.py    From octavia with 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 #13
Source File: ptyprocess.py    From sublime_debugger with 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 #14
Source File: _pexpect.py    From Computable with 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 #15
Source File: pexpect.py    From smod-1 with 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 #16
Source File: daemon.py    From pycepa with 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 #17
Source File: test_functional.py    From cotyledon with 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 #18
Source File: streamcards.py    From mtgencode with MIT License 5 votes vote down vote up
def install_suicide_handlers():
    for sig in [signal.SIGHUP, signal.SIGINT, signal.SIGQUIT]:
        signal.signal(sig, handler_kill_self) 
Example #19
Source File: acehttp.py    From HTTPAceProxy with GNU General Public License v3.0 5 votes vote down vote up
def _reloadconfig(signum=None, frame=None):
    '''
    Reload configuration file.
    SIGHUP handler.
    '''
    global AceConfig

    logger = logging.getLogger('reloadconfig')
    reload(aceconfig)
    from aceconfig import AceConfig
    #### Initial settings for AceHTTPproxy host IP
    if AceConfig.httphost == 'auto': AceConfig.httphost = get_ip_address()
    logger.info('Ace Stream HTTP Proxy config reloaded.....') 
Example #20
Source File: test_unix_events.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_remove_signal_handler_error2(self, m_signal):
        m_signal.NSIG = signal.NSIG
        self.loop.add_signal_handler(signal.SIGHUP, lambda: True)

        class Err(OSError):
            errno = errno.EINVAL
        m_signal.signal.side_effect = Err

        self.assertRaises(
            RuntimeError, self.loop.remove_signal_handler, signal.SIGHUP) 
Example #21
Source File: smarthome.py    From smarthome with GNU General Public License v3.0 5 votes vote down vote up
def _reload_logics():
    """
    Reload logics through the commandline with option -l
    """
    pid = lib.daemon.read_pidfile(PIDFILE)
    if pid:
        os.kill(pid, signal.SIGHUP)


#####################################################################
# Main
##################################################################### 
Example #22
Source File: test_journal.py    From networking-odl with Apache License 2.0 5 votes vote down vote up
def test_reset_called_on_sighup(self):
        pid, c2p_read = self._create_periodic_processor_ipc_fork('reset')

        self.assert_process_running(pid)

        os.kill(pid, signal.SIGHUP)

        self.assert_ipc_mock_called(c2p_read) 
Example #23
Source File: test_journal.py    From networking-odl with Apache License 2.0 5 votes vote down vote up
def test_handle_sighup_gracefully(self):
        real_reset = worker.JournalPeriodicProcessor.reset
        pid, c2p_read = self._create_periodic_processor_ipc_fork('reset',
                                                                 real_reset)

        cmd = self.assert_process_running(pid)

        os.kill(pid, signal.SIGHUP)

        self.assert_ipc_mock_called(c2p_read)

        new_cmd = self.assert_process_running(pid)
        self.assertEqual(cmd, new_cmd) 
Example #24
Source File: daemon.py    From shadowsocksr with Apache License 2.0 5 votes vote down vote up
def daemon_start(pid_file, log_file):

    def handle_exit(signum, _):
        if signum == signal.SIGTERM:
            sys.exit(0)
        sys.exit(1)

    signal.signal(signal.SIGINT, handle_exit)
    signal.signal(signal.SIGTERM, handle_exit)

    # fork only once because we are sure parent will exit
    pid = os.fork()
    assert pid != -1

    if pid > 0:
        # parent waits for its child
        time.sleep(5)
        sys.exit(0)

    # child signals its parent to exit
    ppid = os.getppid()
    pid = os.getpid()
    if write_pid_file(pid_file, pid) != 0:
        os.kill(ppid, signal.SIGINT)
        sys.exit(1)

    os.setsid()
    signal.signal(signal.SIG_IGN, signal.SIGHUP)

    print('started')
    os.kill(ppid, signal.SIGTERM)

    sys.stdin.close()
    try:
        freopen(log_file, 'a', sys.stdout)
        freopen(log_file, 'a', sys.stderr)
    except IOError as e:
        shell.print_exception(e)
        sys.exit(1) 
Example #25
Source File: ptys.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
def terminate(self, force = True):
		"""Send a signal to the process in the pty"""
		if self.proc.isalive():

			if os.name == 'nt':
				signals = [signal.SIGINT, signal.SIGTERM]
			else:
				signals = [signal.SIGHUP, signal.SIGCONT, signal.SIGINT,
						   signal.SIGTERM]

			try:
				for sig in signals:
					self.proc.kill(sig)

					if not self.proc.isalive():
						return True

				if force:
					self.proc.kill(signal.SIGKILL)

					if not self.proc.isalive():
						return True

				return False

			except Exception as e:
				if self.proc.isalive():
					return False

		return True 
Example #26
Source File: daemon.py    From Telebix with GNU General Public License v3.0 5 votes vote down vote up
def stop(self):
        """
        Stop the daemon
        """

        if self.verbose >= 1:
            pass

        # Get the pid from the pidfile
        pid = self.get_pid()

        if not pid:

            if os.path.exists(self.pidfile):
                os.remove(self.pidfile)

            return  # Not an error in a restart

        # Try killing the daemon process
        try:
            i = 0
            while 1:
                os.kill(pid, signal.SIGTERM)
                time.sleep(0.1)
                i = i + 1
                if i % 10 == 0:
                    os.kill(pid, signal.SIGHUP)
        except OSError as err:
            if err.errno == errno.ESRCH:
                if os.path.exists(self.pidfile):
                    os.remove(self.pidfile)
            else:
                print(str(err))
                sys.exit(1)

        pass 
Example #27
Source File: fcgi.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def _installSignalHandlers(self):
        self._oldSIGs = [(x,signal.getsignal(x)) for x in
                         (signal.SIGHUP, signal.SIGINT, signal.SIGTERM)]
        signal.signal(signal.SIGHUP, self._hupHandler)
        signal.signal(signal.SIGINT, self._intHandler)
        signal.signal(signal.SIGTERM, self._intHandler) 
Example #28
Source File: proctools.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def hangup(self):
        os.kill(self.childpid, SIGHUP) 
Example #29
Source File: exit.py    From pscheduler with Apache License 2.0 5 votes vote down vote up
def set_graceful_exit():
    """
    Set up a graceful exit when certain signals arrive.
    """

    for sig in [signal.SIGHUP,
                signal.SIGINT,
                signal.SIGQUIT,
                signal.SIGTERM]:
        signal.signal(sig, __exit_handler) 
Example #30
Source File: daemon.py    From LearningApacheSpark with MIT License 5 votes vote down vote up
def worker(sock, authenticated):
    """
    Called by a worker process after the fork().
    """
    signal.signal(SIGHUP, SIG_DFL)
    signal.signal(SIGCHLD, SIG_DFL)
    signal.signal(SIGTERM, SIG_DFL)
    # restore the handler for SIGINT,
    # it's useful for debugging (show the stacktrace before exit)
    signal.signal(SIGINT, signal.default_int_handler)

    # Read the socket using fdopen instead of socket.makefile() because the latter
    # seems to be very slow; note that we need to dup() the file descriptor because
    # otherwise writes also cause a seek that makes us miss data on the read side.
    infile = os.fdopen(os.dup(sock.fileno()), "rb", 65536)
    outfile = os.fdopen(os.dup(sock.fileno()), "wb", 65536)

    if not authenticated:
        client_secret = UTF8Deserializer().loads(infile)
        if os.environ["PYTHON_WORKER_FACTORY_SECRET"] == client_secret:
            write_with_length("ok".encode("utf-8"), outfile)
            outfile.flush()
        else:
            write_with_length("err".encode("utf-8"), outfile)
            outfile.flush()
            sock.close()
            return 1

    exit_code = 0
    try:
        worker_main(infile, outfile)
    except SystemExit as exc:
        exit_code = compute_real_exit_code(exc.code)
    finally:
        try:
            outfile.flush()
        except Exception:
            pass
    return exit_code