Python signal.SIGUSR1 Examples

The following are 30 code examples for showing how to use signal.SIGUSR1(). 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: multibootusb   Author: mbusb   File: osdriver.py    License: GNU General Public License v2.0 6 votes vote down vote up
def dd_iso_image_readoutput(self, dd_process, gui_update, in_file_size,
                                output_q):
        # If this time delay is not given, the Popen does not execute
        # the actual command
        time.sleep(0.1)
        dd_process.send_signal(signal.SIGUSR1)
        dd_process.stderr.flush()
        while True:
            time.sleep(0.1)
            out_error = dd_process.stderr.readline().decode()
            if out_error:
                if 'bytes' in out_error:
                    bytes_copied = float(out_error.split(' ', 1)[0])
                    gui_update( bytes_copied / in_file_size * 100. )
                    break
                if 15 < output_q.qsize():
                    output_q.get()
                output_q.put(out_error.rstrip())
            else:
                # stderr is closed
                break 
Example 2
Project: ironpython2   Author: IronLanguages   File: test_multiprocessing.py    License: 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 3
Project: ironpython2   Author: IronLanguages   File: test_multiprocessing.py    License: 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 4
Project: ironpython2   Author: IronLanguages   File: test_threadsignals.py    License: 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 5
Project: avocado-vt   Author: avocado-framework   File: virtio_console_guest.py    License: 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 6
Project: BinderFilter   Author: dxwu   File: test_multiprocessing.py    License: 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 7
Project: BinderFilter   Author: dxwu   File: test_threadsignals.py    License: 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 8
Project: oss-ftp   Author: aliyun   File: test_multiprocessing.py    License: 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 9
Project: oss-ftp   Author: aliyun   File: test_multiprocessing.py    License: 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 10
Project: oss-ftp   Author: aliyun   File: test_threadsignals.py    License: 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 11
Project: Safejumper-for-Desktop   Author: proxysh   File: test_process.py    License: 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 12
Project: pscheduler   Author: perfsonar   File: log_test.py    License: 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 13
Project: Fluid-Designer   Author: Microvellum   File: test_signal.py    License: 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 14
Project: Fluid-Designer   Author: Microvellum   File: test_subprocess.py    License: 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 15
Project: Fluid-Designer   Author: Microvellum   File: _test_multiprocessing.py    License: 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 16
Project: rtp_cluster   Author: sippy   File: SipLogger.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, app, call_id = 'GLOBAL', logfile = '/var/log/sip.log'):
        self.itime = time()
        self.app = '/%s' % app
        self.call_id = call_id
        bend = os.environ.get('SIPLOG_BEND', 'stderr').lower()
        tform = os.environ.get('SIPLOG_TFORM', 'abs').lower()
        if tform == 'rel':
            self.offstime = True
            itime = os.environ.get('SIPLOG_TSTART', self.itime)
            self.itime = float(itime)
        self.level = eval('SIPLOG_' + os.environ.get('SIPLOG_LVL', 'INFO'))
        if bend == 'stderr':
            self.write = self.write_stderr
        elif bend == 'none':
            self.write = self.donoting
        else:
            self.write = self.write_logfile
            self.wi_available = Condition()
            self.wi = []
            if bend != 'syslog':
                self.logger = AsyncLogger(app, self)
                self.logfile = os.environ.get('SIPLOG_LOGFILE_FILE', logfile)
                self.signal_handler = LogSignal(self, SIGUSR1, self.reopen)
            else:
                self.logger = AsyncLoggerSyslog(app, self)
                self.app = '' 
Example 17
Project: sanic   Author: huge-success   File: worker.py    License: MIT License 5 votes vote down vote up
def init_signals(self):
        # Set up signals through the event loop API.

        self.loop.add_signal_handler(
            signal.SIGQUIT, self.handle_quit, signal.SIGQUIT, None
        )

        self.loop.add_signal_handler(
            signal.SIGTERM, self.handle_exit, signal.SIGTERM, None
        )

        self.loop.add_signal_handler(
            signal.SIGINT, self.handle_quit, signal.SIGINT, None
        )

        self.loop.add_signal_handler(
            signal.SIGWINCH, self.handle_winch, signal.SIGWINCH, None
        )

        self.loop.add_signal_handler(
            signal.SIGUSR1, self.handle_usr1, signal.SIGUSR1, None
        )

        self.loop.add_signal_handler(
            signal.SIGABRT, self.handle_abort, signal.SIGABRT, None
        )

        # Don't let SIGTERM and SIGUSR1 disturb active requests
        # by interrupting system calls
        signal.siginterrupt(signal.SIGTERM, False)
        signal.siginterrupt(signal.SIGUSR1, False) 
Example 18
Project: qutebrowser   Author: qutebrowser   File: test_editor_bdd.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_up_editor_wait(quteproc, tmpdir, text, editor_pid_watcher):
    """Set up editor.command to a small python script inserting a text."""
    assert not utils.is_windows
    pidfile = tmpdir / 'editor_pid'
    script = tmpdir / 'script.py'
    script.write(textwrap.dedent("""
        import os
        import sys
        import time
        import signal

        def handle(sig, _frame):
            filename = sys.argv[1]
            old_mtime = new_mtime = os.stat(filename).st_mtime
            while old_mtime == new_mtime:
                time.sleep(0.1)
                with open(filename, 'w', encoding='utf-8') as f:
                    f.write({text!r})
                new_mtime = os.stat(filename).st_mtime
            if sig == signal.SIGUSR1:
                sys.exit(0)

        signal.signal(signal.SIGUSR1, handle)
        signal.signal(signal.SIGUSR2, handle)

        with open(r'{pidfile}', 'w') as f:
            f.write(str(os.getpid()))

        time.sleep(100)
    """.format(pidfile=pidfile, text=text)))
    editor = json.dumps([sys.executable, str(script), '{}'])
    quteproc.set_setting('editor.command', editor) 
Example 19
Project: qutebrowser   Author: qutebrowser   File: test_editor_bdd.py    License: GNU General Public License v3.0 5 votes vote down vote up
def kill_editor_wait(tmpdir):
    """Kill the waiting editor."""
    pidfile = tmpdir / 'editor_pid'
    pid = int(pidfile.read())
    # windows has no SIGUSR1, but we don't run this on windows anyways
    # for posix, there IS a member so we need to ignore useless-suppression
    # pylint: disable=no-member,useless-suppression
    os.kill(pid, signal.SIGUSR1) 
Example 20
Project: qutebrowser   Author: qutebrowser   File: earlyinit.py    License: GNU General Public License v3.0 5 votes vote down vote up
def init_faulthandler(fileobj=sys.__stderr__):
    """Enable faulthandler module if available.

    This print a nice traceback on segfaults.

    We use sys.__stderr__ instead of sys.stderr here so this will still work
    when sys.stderr got replaced, e.g. by "Python Tools for Visual Studio".

    Args:
        fobj: An opened file object to write the traceback to.
    """
    if fileobj is None:
        # When run with pythonw.exe, sys.__stderr__ can be None:
        # https://docs.python.org/3/library/sys.html#sys.__stderr__
        # If we'd enable faulthandler in that case, we just get a weird
        # exception, so we don't enable faulthandler if we have no stdout.
        #
        # Later when we have our data dir available we re-enable faulthandler
        # to write to a file so we can display a crash to the user at the next
        # start.
        return
    faulthandler.enable(fileobj)
    if (hasattr(faulthandler, 'register') and hasattr(signal, 'SIGUSR1') and
            sys.stderr is not None):
        # If available, we also want a traceback on SIGUSR1.
        # pylint: disable=no-member,useless-suppression
        faulthandler.register(signal.SIGUSR1)
        # pylint: enable=no-member,useless-suppression 
Example 21
Project: knx   Author: mfussenegger   File: actor.py    License: MIT License 5 votes vote down vote up
def main():
    """
    Monitor telegrams for a specific actor and toggle it's state using kill -USR1

    Usage:
        python example_actor.py eibd_host[:port] actor_address

    Example:
        python example_actor.py localhost '0/0/20'
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("host", type=str)
    parser.add_argument("actor", type=str)
    args = parser.parse_args()

    host, port = parse_host_and_port(args.host)
    print('Creating connection to {host}:{port}'.format(host=host, port=port))

    conn = connect(host=host, port=port)
    actor = Actor(args.actor, conn.write)
    loop = asyncio.get_event_loop()
    loop.add_signal_handler(signal.SIGUSR1, actor.toggle)
    print('Use "kill -USR1 {pid}" to toggle state'.format(pid=os.getpid()))
    loop.call_soon(lambda: conn.read(actor.address))  # read request for initial state
    try:
        loop.run_until_complete(conn.bus_monitor(actor))
    except KeyboardInterrupt:
        print('Byte')
    finally:
        loop.close() 
Example 22
Project: jbox   Author: jpush   File: arbiter.py    License: MIT License 5 votes vote down vote up
def handle_usr1(self):
        """\
        SIGUSR1 handling.
        Kill all workers by sending them a SIGUSR1
        """
        self.log.reopen_files()
        self.kill_workers(signal.SIGUSR1) 
Example 23
Project: ChromaTerm   Author: hSaria   File: cli.py    License: MIT License 5 votes vote down vote up
def reload_chromaterm_instances():
    """Reloads other ChromaTerm CLI instances by sending them signal.SIGUSR1.

    Returns:
        The number of processes reloaded.
    """
    import psutil

    count = 0
    current_process = psutil.Process()

    for process in psutil.process_iter():
        if process.pid == current_process.pid:  # Skip the current process
            continue

        try:
            # Only compare the first two arguments (Python and script paths)
            if process.cmdline()[:2] == current_process.cmdline()[:2]:
                os.kill(process.pid, signal.SIGUSR1)
                count += 1
        # As per the documentation, expect those errors when accessing the
        # methods of a process
        except (psutil.AccessDenied, psutil.NoSuchProcess):
            pass

    return count 
Example 24
Project: crosentgec   Author: nusnlp   File: multiprocessing_train.py    License: GNU General Public License v3.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 25
Project: crosentgec   Author: nusnlp   File: multiprocessing_train.py    License: GNU General Public License v3.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 26
Project: cf-mendix-buildpack   Author: mendix   File: start.py    License: Apache License 2.0 5 votes vote down vote up
def sigusr_handler(_signo, _stack_frame):
            if _signo == signal.SIGUSR1:
                emit(jvm={"errors": 1.0})
            elif _signo == signal.SIGUSR2:
                emit(jvm={"ooms": 1.0})
            else:
                # Should not happen
                pass
            m2ee.stop()
            sys.exit(1) 
Example 27
Project: AI-Robot-Challenge-Lab   Author: microsoft   File: runtime_test.py    License: MIT License 5 votes vote down vote up
def exit_properly_runtime_test():
    f = open("result.txt", "w")
    f.write("0")
    f.close()
    rospy.signal_shutdown("SUCCESS TEST")
    os.kill(os.getpid(), signal.SIGUSR1)
    sys.exit(0) 
Example 28
Project: AI-Robot-Challenge-Lab   Author: microsoft   File: runtime_test.py    License: MIT License 5 votes vote down vote up
def start_countdown(seconds):
    def timeout_countdown(seconds):
        time.sleep(seconds)
        rospy.logfatal("COUNTDOWN ERROR RUNTIME TEST")
        os.kill(os.getpid(), signal.SIGUSR1)
        sys.exit(1)
        
    t= Thread(target = lambda: timeout_countdown(seconds))
    t.start()
#---------------------------------------------
# launch countdown 
Example 29
Project: ironpython2   Author: IronLanguages   File: test_signal.py    License: Apache License 2.0 5 votes vote down vote up
def test_setting_signal_handler_to_none_raises_error(self):
        self.assertRaises(TypeError, signal.signal,
                          signal.SIGUSR1, None) 
Example 30
Project: ironpython2   Author: IronLanguages   File: test_signal.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        """Install a no-op signal handler that can be set to allow
        interrupts or not, and arrange for the original signal handler to be
        re-installed when the test is finished.
        """
        self.signum = signal.SIGUSR1
        oldhandler = signal.signal(self.signum, lambda x,y: None)
        self.addCleanup(signal.signal, self.signum, oldhandler)