Python signal.SIGALRM Examples

The following are 30 code examples for showing how to use signal.SIGALRM(). 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: ironpython2   Author: IronLanguages   File: test_subprocess.py    License: Apache License 2.0 6 votes vote down vote up
def test_communicate_eintr(self):
        # Issue #12493: communicate() should handle EINTR
        def handler(signum, frame):
            pass
        old_handler = signal.signal(signal.SIGALRM, handler)
        self.addCleanup(signal.signal, signal.SIGALRM, old_handler)

        # the process is running for 2 seconds
        args = [sys.executable, "-c", 'import time; time.sleep(2)']
        for stream in ('stdout', 'stderr'):
            kw = {stream: subprocess.PIPE}
            with subprocess.Popen(args, **kw) as process:
                signal.alarm(1)
                try:
                    # communicate() will be interrupted by SIGALRM
                    process.communicate()
                finally:
                    signal.alarm(0) 
Example 2
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 3
Project: n6   Author: CERT-Polska   File: timeout_callback_manager.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _reproduce_preserved_alarm_stuff(self):
        preserved = self._preserved_alarm_data
        if preserved is not None:
            assert preserved.handler is not None
            # set the preserved handler as well as timeout and repeat
            # interval (if any; note: if the timeout has already passed
            # it will be set, by `_set_nonzero_alarm()`, to `MINIMAL_TIMEOUT`)
            self._signal(signal.SIGALRM, preserved.handler)
            if preserved.timeout:
                already_elapsed = time.time() - preserved.preserved_at
                self._store_alarm(preserved.timeout - already_elapsed, preserved.repeat_interval)
            else:
                self._store_alarm(0)
            self._clear_preserved_alarm_data()
        else:
            self._store_alarm(0) 
Example 4
Project: qdb   Author: quantopian   File: test_misc.py    License: Apache License 2.0 6 votes vote down vote up
def test_timeout_start(self, test_name, exc, assertion):
        """
        Tests running a timeout with the start method that will raise itself.
        """
        tsignal = signal.SIGALRM
        existing_handler = signal.getsignal(tsignal)
        t = QdbTimeout(1, exc)
        t.start()
        with self.assertRaises(Exception) as cm:
            self.assertTrue(t.pending)
            time.sleep(2)
            if exc:
                self.fail('Timeout did not stop the sleep')

        self.assertIs(cm.exception, exc or t)
        self.assertIs(signal.getsignal(tsignal), existing_handler) 
Example 5
Project: qdb   Author: quantopian   File: test_misc.py    License: Apache License 2.0 6 votes vote down vote up
def test_timeout_ctx_mgr(self, test_name, exc, assertion):
        tsignal = signal.SIGALRM
        existing_handler = signal.getsignal(tsignal)
        try:
            with QdbTimeout(1, exc) as t:
                self.assertTrue(t.pending)
                time.sleep(2)
                if exc:
                    self.fail('Timeout did not stop the sleep')
        except Exception as u:
            assertion(self, u, t)
        else:
            self.assertIs(
                exc,
                False,
                'QdbTimeout(1, False) should not raise an exception'
            )

        self.assertIs(signal.getsignal(tsignal), existing_handler) 
Example 6
Project: Fluid-Designer   Author: Microvellum   File: test_io.py    License: GNU General Public License v3.0 6 votes vote down vote up
def check_reentrant_write(self, data, **fdopen_kwargs):
        def on_alarm(*args):
            # Will be called reentrantly from the same thread
            wio.write(data)
            1/0
        signal.signal(signal.SIGALRM, on_alarm)
        r, w = os.pipe()
        wio = self.io.open(w, **fdopen_kwargs)
        try:
            signal.alarm(1)
            # Either the reentrant call to wio.write() fails with RuntimeError,
            # or the signal handler raises ZeroDivisionError.
            with self.assertRaises((ZeroDivisionError, RuntimeError)) as cm:
                while 1:
                    for i in range(100):
                        wio.write(data)
                        wio.flush()
                    # Make sure the buffer doesn't fill up and block further writes
                    os.read(r, len(data) * 100)
            exc = cm.exception
            if isinstance(exc, RuntimeError):
                self.assertTrue(str(exc).startswith("reentrant call"), str(exc))
        finally:
            wio.close()
            os.close(r) 
Example 7
Project: Fluid-Designer   Author: Microvellum   File: test_selectors.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_select_interrupt_exc(self):
        s = self.SELECTOR()
        self.addCleanup(s.close)

        rd, wr = self.make_socketpair()

        class InterruptSelect(Exception):
            pass

        def handler(*args):
            raise InterruptSelect

        orig_alrm_handler = signal.signal(signal.SIGALRM, handler)
        self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
        self.addCleanup(signal.alarm, 0)

        signal.alarm(1)

        s.register(rd, selectors.EVENT_READ)
        t = time()
        # select() is interrupted by a signal which raises an exception
        with self.assertRaises(InterruptSelect):
            s.select(30)
        # select() was interrupted before the timeout of 30 seconds
        self.assertLess(time() - t, 5.0) 
Example 8
Project: Fluid-Designer   Author: Microvellum   File: test_selectors.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_select_interrupt_noraise(self):
        s = self.SELECTOR()
        self.addCleanup(s.close)

        rd, wr = self.make_socketpair()

        orig_alrm_handler = signal.signal(signal.SIGALRM, lambda *args: None)
        self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
        self.addCleanup(signal.alarm, 0)

        signal.alarm(1)

        s.register(rd, selectors.EVENT_READ)
        t = time()
        # select() is interrupted by a signal, but the signal handler doesn't
        # raise an exception, so select() should by retries with a recomputed
        # timeout
        self.assertFalse(s.select(1.5))
        self.assertGreaterEqual(time() - t, 1.0) 
Example 9
Project: Fluid-Designer   Author: Microvellum   File: test_threadsignals.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_rlock_acquire_interruption(self):
        # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
        # in a deadlock.
        # XXX this test can fail when the legacy (non-semaphore) implementation
        # of locks is used in thread_pthread.h, see issue #11223.
        oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
        try:
            rlock = thread.RLock()
            # For reentrant locks, the initial acquisition must be in another
            # thread.
            def other_thread():
                rlock.acquire()
            thread.start_new_thread(other_thread, ())
            # Wait until we can't acquire it without blocking...
            while rlock.acquire(blocking=False):
                rlock.release()
                time.sleep(0.01)
            signal.alarm(1)
            t1 = time.time()
            self.assertRaises(KeyboardInterrupt, rlock.acquire, timeout=5)
            dt = time.time() - t1
            # See rationale above in test_lock_acquire_interruption
            self.assertLess(dt, 3.0)
        finally:
            signal.signal(signal.SIGALRM, oldalrm) 
Example 10
Project: pyFileFixity   Author: lrq3000   File: profiler.py    License: MIT License 6 votes vote down vote up
def start(self):
        self.last_profile_time = timer()

        if self.use_signal:
            try:
                signal.signal(signal.SIGALRM, self._signal)
                # the following tells the system to restart interrupted system calls if they are
                # interrupted before any data has been transferred. This avoids many of the problems
                # related to signals interrupting system calls, see issue #16
                signal.siginterrupt(signal.SIGALRM, False)
            except ValueError:
                raise NotMainThreadError()

            signal.setitimer(signal.ITIMER_REAL, self.interval, 0.0)
        else:
            sys.setprofile(self._profile) 
Example 11
Project: ironpython2   Author: IronLanguages   File: test_pty.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        # isatty() and close() can hang on some platforms.  Set an alarm
        # before running the test to make sure we don't hang forever.
        old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
        self.addCleanup(signal.signal, signal.SIGALRM, old_alarm)
        self.addCleanup(signal.alarm, 0)
        signal.alarm(10) 
Example 12
Project: ironpython2   Author: IronLanguages   File: test_threadsignals.py    License: Apache License 2.0 5 votes vote down vote up
def registerSignals(for_usr1, for_usr2, for_alrm):
    usr1 = signal.signal(signal.SIGUSR1, for_usr1)
    usr2 = signal.signal(signal.SIGUSR2, for_usr2)
    alrm = signal.signal(signal.SIGALRM, for_alrm)
    return usr1, usr2, alrm


# The signal handler. Just note that the signal occurred and
# from who. 
Example 13
Project: ironpython2   Author: IronLanguages   File: test_threadsignals.py    License: Apache License 2.0 5 votes vote down vote up
def test_main():
    global signal_blackboard

    signal_blackboard = { signal.SIGUSR1 : {'tripped': 0, 'tripped_by': 0 },
                          signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 },
                          signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } }

    oldsigs = registerSignals(handle_signals, handle_signals, handle_signals)
    try:
        run_unittest(ThreadSignals)
    finally:
        registerSignals(*oldsigs) 
Example 14
Project: OpenMTC   Author: OpenMTC   File: timeout.py    License: Eclipse Public License 1.0 5 votes vote down vote up
def timeout(seconds):
    if not seconds:
        yield
        return
    
    original_handler = signal(SIGALRM, noop)

    try:
        alarm(seconds)
        yield
    finally:
        alarm(0)
        signal(SIGALRM, original_handler) 
Example 15
Project: Yuki-Chan-The-Auto-Pentest   Author: Yukinoshita47   File: timeout.py    License: MIT License 5 votes vote down vote up
def limitedTime(second, func, *args, **kw):
            second = fixTimeout(second)
            old_alarm = signal(SIGALRM, signalHandler)
            try:
                alarm(second)
                return func(*args, **kw)
            finally:
                alarm(0)
                signal(SIGALRM, old_alarm) 
Example 16
Project: ITWSV   Author: penetrate2hack   File: timeout.py    License: MIT License 5 votes vote down vote up
def limitedTime(second, func, *args, **kw):
            second = fixTimeout(second)
            old_alarm = signal(SIGALRM, signalHandler)
            try:
                alarm(second)
                return func(*args, **kw)
            finally:
                alarm(0)
                signal(SIGALRM, old_alarm) 
Example 17
Project: BinderFilter   Author: dxwu   File: test_subprocess.py    License: MIT License 5 votes vote down vote up
def test_communicate_eintr(self):
        # Issue #12493: communicate() should handle EINTR
        def handler(signum, frame):
            pass
        old_handler = signal.signal(signal.SIGALRM, handler)
        self.addCleanup(signal.signal, signal.SIGALRM, old_handler)

        # the process is running for 2 seconds
        args = [sys.executable, "-c", 'import time; time.sleep(2)']
        for stream in ('stdout', 'stderr'):
            kw = {stream: subprocess.PIPE}
            with subprocess.Popen(args, **kw) as process:
                signal.alarm(1)
                # communicate() will be interrupted by SIGALRM
                process.communicate() 
Example 18
Project: BinderFilter   Author: dxwu   File: test_threadsignals.py    License: MIT License 5 votes vote down vote up
def registerSignals(for_usr1, for_usr2, for_alrm):
    usr1 = signal.signal(signal.SIGUSR1, for_usr1)
    usr2 = signal.signal(signal.SIGUSR2, for_usr2)
    alrm = signal.signal(signal.SIGALRM, for_alrm)
    return usr1, usr2, alrm


# The signal handler. Just note that the signal occurred and
# from who. 
Example 19
Project: BinderFilter   Author: dxwu   File: test_threadsignals.py    License: MIT License 5 votes vote down vote up
def test_main():
    global signal_blackboard

    signal_blackboard = { signal.SIGUSR1 : {'tripped': 0, 'tripped_by': 0 },
                          signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 },
                          signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } }

    oldsigs = registerSignals(handle_signals, handle_signals, handle_signals)
    try:
        run_unittest(ThreadSignals)
    finally:
        registerSignals(*oldsigs) 
Example 20
Project: oss-ftp   Author: aliyun   File: test_subprocess.py    License: MIT License 5 votes vote down vote up
def test_communicate_eintr(self):
        # Issue #12493: communicate() should handle EINTR
        def handler(signum, frame):
            pass
        old_handler = signal.signal(signal.SIGALRM, handler)
        self.addCleanup(signal.signal, signal.SIGALRM, old_handler)

        # the process is running for 2 seconds
        args = [sys.executable, "-c", 'import time; time.sleep(2)']
        for stream in ('stdout', 'stderr'):
            kw = {stream: subprocess.PIPE}
            with subprocess.Popen(args, **kw) as process:
                signal.alarm(1)
                # communicate() will be interrupted by SIGALRM
                process.communicate() 
Example 21
Project: oss-ftp   Author: aliyun   File: test_threadsignals.py    License: MIT License 5 votes vote down vote up
def registerSignals(for_usr1, for_usr2, for_alrm):
    usr1 = signal.signal(signal.SIGUSR1, for_usr1)
    usr2 = signal.signal(signal.SIGUSR2, for_usr2)
    alrm = signal.signal(signal.SIGALRM, for_alrm)
    return usr1, usr2, alrm


# The signal handler. Just note that the signal occurred and
# from who. 
Example 22
Project: oss-ftp   Author: aliyun   File: test_threadsignals.py    License: MIT License 5 votes vote down vote up
def test_main():
    global signal_blackboard

    signal_blackboard = { signal.SIGUSR1 : {'tripped': 0, 'tripped_by': 0 },
                          signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 },
                          signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } }

    oldsigs = registerSignals(handle_signals, handle_signals, handle_signals)
    try:
        run_unittest(ThreadSignals)
    finally:
        registerSignals(*oldsigs) 
Example 23
Project: cotyledon   Author: sileht   File: _utils.py    License: Apache License 2.0 5 votes vote down vote up
def _signal_catcher(self, sig, frame):
        # NOTE(sileht): This is useful only for python < 3.5
        # in python >= 3.5 we could read the signal number
        # from the wakeup_fd pipe
        if sig in (SIGALRM, signal.SIGTERM):
            self._signals_received.appendleft(sig)
        else:
            self._signals_received.append(sig) 
Example 24
Project: deepWordBug   Author: QData   File: ext_alarm.py    License: Apache License 2.0 5 votes vote down vote up
def alarm_handler(app, signum, frame):
    if signum == signal.SIGALRM:
        app.log.error(app.alarm.msg) 
Example 25
Project: deepWordBug   Author: QData   File: ext_alarm.py    License: Apache License 2.0 5 votes vote down vote up
def set(self, time, msg):
        """
        Set the application alarm to ``time`` seconds.  If the time is
        exceeded ``signal.SIGALRM`` is raised.

        :param time: The time in seconds to set the alarm to.
        :param msg: The message to display if the alarm is triggered.
        """

        LOG.debug('setting application alarm for %s seconds' % time)
        self.msg = msg
        signal.alarm(int(time)) 
Example 26
Project: deepWordBug   Author: QData   File: ext_alarm.py    License: Apache License 2.0 5 votes vote down vote up
def load(app):
    app.catch_signal(signal.SIGALRM)
    app.extend('alarm', AlarmManager())
    app.hook.register('signal', alarm_handler) 
Example 27
Project: n6   Author: CERT-Polska   File: timeout_callback_manager.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _set_up_custom_alarm_stuff(self):
        custom_handler = self._get_concurrency_protection_wrapped_handler(
            self._custom_alarm_handler_of_TimeoutCallbackManager)
        assert self._stored_alarm_obj
        prev_alarm = self._stored_alarm_obj
        prev_handler = self._signal(signal.SIGALRM, custom_handler)
        self._set_preserved_alarm_data(prev_handler,
                                       prev_alarm.timeout,
                                       prev_alarm.repeat_interval) 
Example 28
Project: patator   Author: lanjelot   File: patator.py    License: GNU General Public License v2.0 5 votes vote down vote up
def handle_alarm():
  if not on_windows():
    signal.signal(signal.SIGALRM, raise_timeout) 
Example 29
Project: patator   Author: lanjelot   File: patator.py    License: GNU General Public License v2.0 5 votes vote down vote up
def raise_timeout(signum, frame):
  if signum == signal.SIGALRM:
    raise TimeoutError('timed out') 
Example 30
Project: PyxieWPS   Author: jgilhutton   File: pyxiewps-EN-without-Aircrack.py    License: Apache License 2.0 5 votes vote down vote up
def run(self, cmd, shell = False, kill_tree = True, timeout = -1):
    """
    Runs a command witha given time after wich is terminated
    returns stdout of proc.
    output is a list without passing strip() on the lines.
    """

    class Alarm(Exception):
      pass
    def alarm_handler(signum, frame):
      raise Alarm
    if timeout != -1:
      signal(SIGALRM, alarm_handler) # Time's ticking...
      alarm(timeout)                 

    proc = subprocess.Popen(cmd, shell = shell, stdout = subprocess.PIPE)
    output = []
    try:
      for line in iter(proc.stdout.readline, ''):
	output.append(line)
      if timeout != -1:
	alarm(0)
    except Alarm:         # time's out! alarm is raised
      pids = [proc.pid]   # kill the process tree related with the main process.
      if kill_tree:
	pids.extend(self.get_process_children(proc.pid))
      for pid in pids:   
	try:             
	  kill(pid, SIGKILL)
	except OSError:
	  pass
      return output
    return output