Python signal.SIGUSR1 Examples

The following are 30 code examples of signal.SIGUSR1(). 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: test_multiprocessing.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_poll_eintr(self):
        got_signal = [False]
        def record(*args):
            got_signal[0] = True
        pid = os.getpid()
        oldhandler = signal.signal(signal.SIGUSR1, record)
        try:
            killer = self.Process(target=self._killer, args=(pid,))
            killer.start()
            p = self.Process(target=time.sleep, args=(1,))
            p.start()
            p.join()
            self.assertTrue(got_signal[0])
            self.assertEqual(p.exitcode, 0)
            killer.join()
        finally:
            signal.signal(signal.SIGUSR1, oldhandler)

#
# Test to verify handle verification, see issue 3321
# 
Example #2
Source File: test_signal.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_pthread_kill_main_thread(self):
        # Test that a signal can be sent to the main thread with pthread_kill()
        # before any other thread has been created (see issue #12392).
        code = """if True:
            import threading
            import signal
            import sys

            def handler(signum, frame):
                sys.exit(3)

            signal.signal(signal.SIGUSR1, handler)
            signal.pthread_kill(threading.get_ident(), signal.SIGUSR1)
            sys.exit(2)
        """

        with spawn_python('-c', code) as process:
            stdout, stderr = process.communicate()
            exitcode = process.wait()
            if exitcode != 3:
                raise Exception("Child error (exit code %s): %s" %
                                (exitcode, stdout)) 
Example #3
Source File: test_subprocess.py    From Fluid-Designer with GNU General Public License v3.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.SIGUSR1, handler)
        self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)

        args = [sys.executable, "-c",
                'import os, signal;'
                'os.kill(os.getppid(), signal.SIGUSR1)']
        for stream in ('stdout', 'stderr'):
            kw = {stream: subprocess.PIPE}
            with subprocess.Popen(args, **kw) as process:
                # communicate() will be interrupted by SIGUSR1
                process.communicate()


    # This test is Linux-ish specific for simplicity to at least have
    # some coverage.  It is not a platform specific bug. 
Example #4
Source File: _test_multiprocessing.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_poll_eintr(self):
        got_signal = [False]
        def record(*args):
            got_signal[0] = True
        pid = os.getpid()
        oldhandler = signal.signal(signal.SIGUSR1, record)
        try:
            killer = self.Process(target=self._killer, args=(pid,))
            killer.start()
            try:
                p = self.Process(target=time.sleep, args=(2,))
                p.start()
                p.join()
            finally:
                killer.join()
            self.assertTrue(got_signal[0])
            self.assertEqual(p.exitcode, 0)
        finally:
            signal.signal(signal.SIGUSR1, oldhandler)

#
# Test to verify handle verification, see issue 3321
# 
Example #5
Source File: test_multiprocessing.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_poll_eintr(self):
        got_signal = [False]
        def record(*args):
            got_signal[0] = True
        pid = os.getpid()
        oldhandler = signal.signal(signal.SIGUSR1, record)
        try:
            killer = self.Process(target=self._killer, args=(pid,))
            killer.start()
            p = self.Process(target=time.sleep, args=(1,))
            p.start()
            p.join()
            self.assertTrue(got_signal[0])
            self.assertEqual(p.exitcode, 0)
            killer.join()
        finally:
            signal.signal(signal.SIGUSR1, oldhandler)

#
# Test to verify handle verification, see issue 3321
# 
Example #6
Source File: log_test.py    From pscheduler with Apache License 2.0 6 votes vote down vote up
def test_log(self):
        """Logging tests"""

        # Not much to test here but exercise the code nonetheless
        # for regression/coverage.

        log = Log(verbose=False, prefix='test')

        log.debug("Invisible debug.")

        try:
            raise ValueError("Test exception")
        except ValueError:
            log.exception("Test exception with message")

        for num in range(1, 5):
            log.debug("Debug")
            log.info("Info")
            log.warning("Warning")
            log.error("Error")
            log.critical("Crtitical")
            os.kill(os.getpid(),
                    signal.SIGUSR1 if (num % 2) != 0 else signal.SIGUSR2) 
Example #7
Source File: test_threadsignals.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_signals(self):
        signalled_all.acquire()
        self.spawnSignallingThread()
        signalled_all.acquire()
        # the signals that we asked the kernel to send
        # will come back, but we don't know when.
        # (it might even be after the thread exits
        # and might be out of order.)  If we haven't seen
        # the signals yet, send yet another signal and
        # wait for it return.
        if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \
           or signal_blackboard[signal.SIGUSR2]['tripped'] == 0:
            try:
                signal.alarm(1)
                signal.pause()
            finally:
                signal.alarm(0)

        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'],
                           thread.get_ident())
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped_by'],
                           thread.get_ident())
        signalled_all.release() 
Example #8
Source File: test_process.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_childSignalHandling(self):
        """
        The disposition of signals which are ignored in the parent
        process is reset to the default behavior for the child
        process.
        """
        # Somewhat arbitrarily select SIGUSR1 here.  It satisfies our
        # requirements that:
        #    - The interpreter not fiddle around with the handler
        #      behind our backs at startup time (this disqualifies
        #      signals like SIGINT and SIGPIPE).
        #    - The default behavior is to exit.
        #
        # This lets us send the signal to the child and then verify
        # that it exits with a status code indicating that it was
        # indeed the signal which caused it to exit.
        which = signal.SIGUSR1

        # Ignore the signal in the parent (and make sure we clean it
        # up).
        handler = signal.signal(which, signal.SIG_IGN)
        self.addCleanup(signal.signal, signal.SIGUSR1, handler)

        # Now do the test.
        return self._testSignal(signal.SIGUSR1) 
Example #9
Source File: test_threadsignals.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_signals(self):
        signalled_all.acquire()
        self.spawnSignallingThread()
        signalled_all.acquire()
        # the signals that we asked the kernel to send
        # will come back, but we don't know when.
        # (it might even be after the thread exits
        # and might be out of order.)  If we haven't seen
        # the signals yet, send yet another signal and
        # wait for it return.
        if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \
           or signal_blackboard[signal.SIGUSR2]['tripped'] == 0:
            signal.alarm(1)
            signal.pause()
            signal.alarm(0)

        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'],
                           thread.get_ident())
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped_by'],
                           thread.get_ident())
        signalled_all.release() 
Example #10
Source File: test_multiprocessing.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_poll_eintr(self):
        got_signal = [False]
        def record(*args):
            got_signal[0] = True
        pid = os.getpid()
        oldhandler = signal.signal(signal.SIGUSR1, record)
        try:
            killer = self.Process(target=self._killer, args=(pid,))
            killer.start()
            p = self.Process(target=time.sleep, args=(1,))
            p.start()
            p.join()
            self.assertTrue(got_signal[0])
            self.assertEqual(p.exitcode, 0)
            killer.join()
        finally:
            signal.signal(signal.SIGUSR1, oldhandler)

#
# Test to verify handle verification, see issue 3321
# 
Example #11
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        """
        Run guest main thread
        """
        global virt
        global exiting
        virt = VirtioGuestPosix()
        slave = Thread(target=worker, args=(virt,))
        slave.start()
        signal.signal(signal.SIGUSR1, sigusr_handler)
        signal.signal(signal.SIGALRM, sigusr_handler)
        while not exiting:
            signal.alarm(1)
            signal.pause()
            catch = virt.catching_signal()
            if catch:
                signal.signal(signal.SIGIO, virt)
            elif catch is False:
                signal.signal(signal.SIGIO, signal.SIG_DFL)
            if catch is not None:
                virt.use_config.set()
        print("PASS: guest_exit")
        sys.exit(0) 
Example #12
Source File: test_multiprocessing.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_ignore_listener(self):
        conn, child_conn = multiprocessing.Pipe()
        try:
            p = multiprocessing.Process(target=self._test_ignore_listener,
                                        args=(child_conn,))
            p.daemon = True
            p.start()
            child_conn.close()
            address = conn.recv()
            time.sleep(0.1)
            os.kill(p.pid, signal.SIGUSR1)
            time.sleep(0.1)
            client = multiprocessing.connection.Client(address)
            self.assertEqual(client.recv(), 'welcome')
            p.join()
        finally:
            conn.close()

#
#
# 
Example #13
Source File: test_threadsignals.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_signals(self):
        signalled_all.acquire()
        self.spawnSignallingThread()
        signalled_all.acquire()
        # the signals that we asked the kernel to send
        # will come back, but we don't know when.
        # (it might even be after the thread exits
        # and might be out of order.)  If we haven't seen
        # the signals yet, send yet another signal and
        # wait for it return.
        if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \
           or signal_blackboard[signal.SIGUSR2]['tripped'] == 0:
            signal.alarm(1)
            signal.pause()
            signal.alarm(0)

        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'],
                           thread.get_ident())
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped_by'],
                           thread.get_ident())
        signalled_all.release() 
Example #14
Source File: test_multiprocessing.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_ignore_listener(self):
        conn, child_conn = multiprocessing.Pipe()
        try:
            p = multiprocessing.Process(target=self._test_ignore_listener,
                                        args=(child_conn,))
            p.daemon = True
            p.start()
            child_conn.close()
            address = conn.recv()
            time.sleep(0.1)
            os.kill(p.pid, signal.SIGUSR1)
            time.sleep(0.1)
            client = multiprocessing.connection.Client(address)
            self.assertEqual(client.recv(), 'welcome')
            p.join()
        finally:
            conn.close()

#
#
# 
Example #15
Source File: queue_processors.py    From zulip with Apache License 2.0 5 votes vote down vote up
def check_and_send_restart_signal() -> None:
    try:
        if not connection.is_usable():
            logging.warning("*** Sending self SIGUSR1 to trigger a restart.")
            os.kill(os.getpid(), signal.SIGUSR1)
    except Exception:
        pass 
Example #16
Source File: multiprocessing_train.py    From training_results_v0.5 with Apache License 2.0 5 votes vote down vote up
def error_listener(self):
        (rank, original_trace) = self.error_queue.get()
        self.error_queue.put((rank, original_trace))
        os.kill(os.getpid(), signal.SIGUSR1) 
Example #17
Source File: multiprocessing_train.py    From training_results_v0.5 with Apache License 2.0 5 votes vote down vote up
def __init__(self, error_queue):
        import signal
        import threading
        self.error_queue = error_queue
        self.children_pids = []
        self.error_thread = threading.Thread(target=self.error_listener, daemon=True)
        self.error_thread.start()
        signal.signal(signal.SIGUSR1, self.signal_handler) 
Example #18
Source File: test_signal.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_sigpending(self):
        code = """if 1:
            import os
            import signal

            def handler(signum, frame):
                1/0

            signum = signal.SIGUSR1
            signal.signal(signum, handler)

            signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
            os.kill(os.getpid(), signum)
            pending = signal.sigpending()
            for sig in pending:
                assert isinstance(sig, signal.Signals), repr(pending)
            if pending != {signum}:
                raise Exception('%s != {%s}' % (pending, signum))
            try:
                signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
            except ZeroDivisionError:
                pass
            else:
                raise Exception("ZeroDivisionError not raised")
        """
        assert_python_ok('-c', code) 
Example #19
Source File: test_signal.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_sigwait_thread(self):
        # Check that calling sigwait() from a thread doesn't suspend the whole
        # process. A new interpreter is spawned to avoid problems when mixing
        # threads and fork(): only async-safe functions are allowed between
        # fork() and exec().
        assert_python_ok("-c", """if True:
            import os, threading, sys, time, signal

            # the default handler terminates the process
            signum = signal.SIGUSR1

            def kill_later():
                # wait until the main thread is waiting in sigwait()
                time.sleep(1)
                os.kill(os.getpid(), signum)

            # the signal must be blocked by all the threads
            signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
            killer = threading.Thread(target=kill_later)
            killer.start()
            received = signal.sigwait([signum])
            if received != signum:
                print("sigwait() received %s, not %s" % (received, signum),
                      file=sys.stderr)
                sys.exit(1)
            killer.join()
            # unblock the signal, which should have been cleared by sigwait()
            signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
        """) 
Example #20
Source File: startup.py    From abusehelper with MIT License 5 votes vote down vote up
def _listen_configs(self, error_event):
        closing = False
        term_count = 0
        configs = frozenset()

        try:
            while True:
                try:
                    while not closing:
                        if frozenset(self._handlers) == configs:
                            configs = yield idiokit.next()
                            configs = frozenset(iter_startups(config.flatten(configs)))
                        yield self._apply(configs, error_event)
                    yield self._wait(self._handlers.values())
                except idiokit.Signal as sig:
                    closing = True

                    if sig.signum == signal.SIGUSR1:
                        self._clean(signal.SIGTERM)
                        continue

                    if sig.signum == signal.SIGUSR2:
                        self._clean(signal.SIGKILL)
                        continue

                    if term_count == 0:
                        self._clean(signal.SIGTERM)
                        term_count += 1
                        continue
                break
        finally:
            self._check() 
Example #21
Source File: commands.py    From abusehelper with MIT License 5 votes vote down vote up
def run_for_instance(self, _, instance):
        yield instance.stop(signal.SIGUSR1)
        yield instance.start() 
Example #22
Source File: commands.py    From abusehelper with MIT License 5 votes vote down vote up
def run_for_instance(self, options, instance):
        if not options.kill:
            yield instance.stop(signal.SIGUSR1)
        else:
            yield instance.stop(signal.SIGUSR2) 
Example #23
Source File: chronograph.py    From openprocurement.auction with Apache License 2.0 5 votes vote down vote up
def run(self):

        LOGGER.info('Starting node: {}'.format(self.server_name))

        def sigterm():
            LOGGER.info('Starting SIGTERM')
            self.scheduler.shutdown(True)

        gevent_signal(signal.SIGTERM, sigterm)

        def sigusr1():
            LOGGER.info('Starting SIGUSR1')
            self.scheduler.shutdown()

        gevent_signal(signal.SIGUSR1, sigusr1)

        for auction_item in iterview(self.config['main']["couch_url"],
                                     self.config['main']['auctions_db'],
                                     'chronograph/start_date'):
            datestamp = (
                datetime.now(self.timezone) + timedelta(minutes=1)
            ).isoformat()
            # ADD FILTER BY VALUE
            # {start: '2016-09-10T14:36:40.378777+03:00', test: false}
            if datestamp < auction_item['value']['start']:
                worker_cmd_provider = \
                    self.mapper(FeedItem(auction_item['value']))
                if not worker_cmd_provider:
                    continue
                self.scheduler.schedule_auction(
                    auction_item['id'], auction_item['value'],
                    args=worker_cmd_provider(auction_item['id'])
                )

            if self.scheduler.exit:
                break

        while not self.scheduler.execution_stopped:
            sleep(10)
            LOGGER.info('Wait until execution stopped') 
Example #24
Source File: test_threadsignals.py    From oss-ftp with MIT License 5 votes vote down vote up
def send_signals():
    os.kill(process_pid, signal.SIGUSR1)
    os.kill(process_pid, signal.SIGUSR2)
    signalled_all.release() 
Example #25
Source File: test_threadsignals.py    From oss-ftp with 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 #26
Source File: eintr_tester.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_sigtimedwait(self):
        t0 = time.monotonic()
        signal.sigtimedwait([signal.SIGUSR1], self.sleep_time)
        dt = time.monotonic() - t0
        self.assertGreaterEqual(dt, self.sleep_time) 
Example #27
Source File: eintr_tester.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_sigwaitinfo(self):
        # Issue #25277: The sleep is a weak synchronization between the parent
        # and the child process. If the sleep is too low, the test hangs on
        # slow or highly loaded systems.
        self.sleep_time = 2.0

        signum = signal.SIGUSR1
        pid = os.getpid()

        old_handler = signal.signal(signum, lambda *args: None)
        self.addCleanup(signal.signal, signum, old_handler)

        code = '\n'.join((
            'import os, time',
            'pid = %s' % os.getpid(),
            'signum = %s' % int(signum),
            'sleep_time = %r' % self.sleep_time,
            'time.sleep(sleep_time)',
            'os.kill(pid, signum)',
        ))

        t0 = time.monotonic()
        proc = self.subprocess(code)
        with kill_on_error(proc):
            # parent
            signal.sigwaitinfo([signum])
            dt = time.monotonic() - t0
            self.assertEqual(proc.wait(), 0)

        self.assertGreaterEqual(dt, self.sleep_time) 
Example #28
Source File: test_multiprocessing.py    From oss-ftp with MIT License 5 votes vote down vote up
def _test_ignore_listener(cls, conn):
        def handler(signum, frame):
            pass
        signal.signal(signal.SIGUSR1, handler)
        l = multiprocessing.connection.Listener()
        conn.send(l.address)
        a = l.accept()
        a.send('welcome') 
Example #29
Source File: test_multiprocessing.py    From oss-ftp with MIT License 5 votes vote down vote up
def _test_ignore(cls, conn):
        def handler(signum, frame):
            pass
        signal.signal(signal.SIGUSR1, handler)
        conn.send('ready')
        x = conn.recv()
        conn.send(x)
        conn.send_bytes(b'x'*(1024*1024))   # sending 1 MB should block 
Example #30
Source File: test_twistd.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_getLogObserverFile(self):
        """
        When C{logfile} contains a file name, L{app.AppLogger._getLogObserver}
        returns a log observer pointing at the specified path, and a signal
        handler rotating the log is installed.
        """
        logFiles = _patchTextFileLogObserver(self.patch)
        filename = self.mktemp()
        logger = UnixAppLogger({"logfile": filename})
        logger._getLogObserver()

        self.assertEqual(len(logFiles), 1)
        self.assertEqual(logFiles[0].path, os.path.abspath(filename))

        self.assertEqual(len(self.signals), 1)
        self.assertEqual(self.signals[0][0], signal.SIGUSR1)

        d = Deferred()

        def rotate():
            d.callback(None)

        logFiles[0].rotate = rotate

        rotateLog = self.signals[0][1]
        rotateLog(None, None)
        return d