def update_wakeup_handler(self, ev=None, disconnected=False):
     if disconnected:
         self.connected = False
         signal.pthread_kill(threading.main_thread().ident, signal.SIGWINCH)
     elif self.connected is None:
         self.connected = True
     self._updates.append(ev)
Exemplo n.º 2
0
def server():
    config_ui_thread = Thread(target=config_ui,
                              args=["", "./piman.yaml", "./hosts.csv"],
                              name="config_ui")
    config_ui_thread.start()

    tftp_thread = Thread(target=tftp.do_tftpd,
                         args=[data_dir, ip, tftp_port],
                         name="tftpd")
    tftp_thread.start()

    dhcp_thread = Thread(
        target=dhcp.do_dhcp,
        args=[mac_ip_file, subnet_mask, ip, lease_time, interface],
        name="dhcpd")
    dhcp_thread.start()

    tcp_thread = Thread(target=tcp.do_tcp,
                        args=[data_dir, tcp_port, ip],
                        name="tcp")
    tcp_thread.start()

    ntp_thread = Thread(target=ntpserver.do_ntp())
    ntp_thread.start()

    dns_thread = Thread(target=dns.start())
    dns_thread.start()

    signal.pthread_kill(config_ui_thread.ident, 15)  # 15 = sigterm
    signal.pthread_kill(tftp_thread.ident, 15)
    signal.pthread_kill(dhcp_thread.ident, 15)
    signal.pthread_kill(tcp_thread.ident, 15)
    signal.pthread_kill(dns_thread, 15)
Exemplo n.º 3
0
 def _signal_int(self, signum, frame):
     """Signal handler for SIGINT - Ctrl+C may have been pressed."""
     self.send_signal(signal.CTRL_C_EVENT if xp.ON_WINDOWS else signum)
     if self.proc is not None and self.proc.poll() is not None:
         self._restore_sigint(frame=frame)
     if xt.on_main_thread() and not xp.ON_WINDOWS:
         signal.pthread_kill(threading.get_ident(), signal.SIGINT)
Exemplo n.º 4
0
 def image_set_pixbuf_thread(self):
     while True:
         image = self.thread_queue.get()
         log.debug('pixbuf_proc [thread]: {}', image.path)
         self.image_set_pixbuf_proc(image)
         self.thread_results.append(image)
         signal.pthread_kill(*self.thread_kill)
Exemplo n.º 5
0
    def shutdown(self, signum, frame):
        for worker in self.worker_list:
            worker.stop_worker()

        # kill the current thread for prevent server reload blocking
        current_thread_id = threading.current_thread().ident
        signal.pthread_kill(current_thread_id, signal.SIGKILL)
Exemplo n.º 6
0
 def interruption():
     inter_iter = iter(self._interruptions)
     while not self._interrupt_event.is_set():
         inter = self._last_attempt = next(inter_iter,
                                           self._last_attempt)
         log.log(self._log_level, inter.message)
         if inter.before_interrupt is not None:
             try:
                 inter.before_interrupt()
             except Exception:
                 log.warning(
                     "Swallowing the error raised by `before_interrupt` hook: %s",
                     inter.before_interrupt,
                     exc_info=True)
         try:
             if inter.interrupt == 'thread':
                 if isinstance(inter.sig, (type(None), BaseException)):
                     exc = TimeoutError(
                         inter.message
                     ) if inter.sig is None else inter.sig
                     raise_in_thread(inter.id, exc)
                 else:
                     # _thread.interrupt_main()
                     signal.pthread_kill(inter.id, inter.sig)
             elif inter.interrupt == 'process':
                 os.kill(inter.id, inter.sig)
         except Exception:
             raise
         finally:
             self._interrupt_event.wait(
                 inter.wait
             )  # retry every second if interruption didn't work
 async def wrapper(*args, **kwargs):
     try:
         ret = await f(*args, **kwargs)
     except Exception:
         logging.exception('Aborting on error')
         signal.pthread_kill(threading.get_ident(), signal.SIGUSR1)
     else:
         return ret
Exemplo n.º 8
0
Arquivo: app.py Projeto: jmpews/torweb
 def stop_loop():
     now = time.time()
     io_loop = tornado.ioloop.IOLoop.instance()
     if now < deadline and (io_loop._callbacks or io_loop._timeouts):
         io_loop.add_timeout(now + 1, stop_loop)
     else:
         io_loop.stop()
         logger.info('...Shutdown...')
         signal.pthread_kill(threading.current_thread().ident, 9)
Exemplo n.º 9
0
def interrupt_main():
    import os
    if os.name == 'nt':
        from _thread import interrupt_main
        interrupt_main()
    else:
        import signal
        import threading
        signal.pthread_kill(threading.main_thread().ident, signal.SIGINT)
Exemplo n.º 10
0
 def stop_loop():
     now = time.time()
     io_loop = tornado.ioloop.IOLoop.instance()
     if now < deadline and (io_loop._callbacks or io_loop._timeouts):
         io_loop.add_timeout(now + 1, stop_loop)
     else:
         io_loop.stop()
         logger.info('...Shutdown...')
         signal.pthread_kill(threading.current_thread().ident, 9)
Exemplo n.º 11
0
    def _onItemFini(self):
        if self.isfini:
            return

        self.printf('connection closed...')

        self.fini()

        if self.loopthread is not None and self.finikill:
            signal.pthread_kill(self.loopthread, signal.SIGINT)
Exemplo n.º 12
0
 def stop(self):
     self._alive = False
     self._wsserver.shutdown()
     self._wsth.join()
     self._sserver.shutdown()
     self._sth.join()
     try:
         signal.pthread_kill(self._myid, signal.SIGINT)
     except Exception:
         pass
Exemplo n.º 13
0
 def stop(self):
     self._alive = False
     self._wsserver.shutdown()
     self._wsth.join()
     self._sserver.shutdown()
     self._sth.join()
     try:
         signal.pthread_kill(self._myid, signal.SIGINT)
     except Exception:
         pass
Exemplo n.º 14
0
    async def command(client, message):

        for client_ in CLIENTS.values():
            await client_.disconnect()

        await client.message_create(message.channel,
                                    'Clients stopped, stopping process.')
        KOKORO.stop()
        thread_id = main_thread().ident
        signal.pthread_kill(thread_id, signal.SIGKILL)
Exemplo n.º 15
0
        def alarm_timeout_handler(signum, frame):
            LOG.warn('Process timed out after %0.f seconds', timeout)
            signal.signal(signal.SIGALRM, signal.SIG_DFL)
            signal.alarm(0)

            if six.PY3:
                signal.pthread_kill(threading.main_thread().ident,
                                    signal.SIGTERM)
            else:
                sys.exit(1)
Exemplo n.º 16
0
        def interrupt():

            if sys.platform == "win32":
                # pthread_kill is Windows only
                from _thread import interrupt_main

                interrupt_main()
            else:
                import signal

                signal.pthread_kill(main_thread, signal.SIGINT)
Exemplo n.º 17
0
def test_signal_delivery(signal_handler):
    dummy = DummyComponent()
    signal_handler.register('dummy', dummy)

    signal_handler.start()
    sleep(1)  # just enough time to get started

    signal.pthread_kill(threading.get_ident(), signal.SIGUSR1)
    sleep(1)  # signal delivery lapse

    assert (dummy._stopped)
Exemplo n.º 18
0
 def handle(self):
     LOG.info('Request received')
     self.request.recv(0)
     LOG.info('Sending %i bytes', len(data))
     self.request.sendall(data)
     LOG.info('Killing server')
     if six.PY3:
         signal.pthread_kill(threading.main_thread().ident,
                             signal.SIGTERM)
     else:
         sys.exit(0)
Exemplo n.º 19
0
 def interruption():
     log.log(log_level, self.message)
     if before_interrupt is not None:
         before_interrupt()
     if interrupt == 'thread':
         if isinstance(self.sig, (type(None), BaseException)):
             raise_in_thread(self.ident, TimeoutError(self.message) if self.sig is None else self.sig)
         else:
             # _thread.interrupt_main()
             signal.pthread_kill(self.ident, self.sig)
     elif interrupt == 'process':
         os.kill(self.ident, self.sig)
Exemplo n.º 20
0
        def interrupt_if_cancelling() -> None:
            # We need to copy the context into this thread, since context is a
            # thread local.
            with prefect.context(context):
                flow_run_id = prefect.context["flow_run_id"]
                while True:
                    exiting_context = done.wait(
                        prefect.config.cloud.check_cancellation_interval)
                    try:
                        self.logger.debug("Checking flow run state...")
                        flow_run_info = self.client.get_flow_run_info(
                            flow_run_id)
                    except Exception:
                        self.logger.warning("Error getting flow run info",
                                            exc_info=True)
                        continue
                    if not flow_run_info.state.is_running():
                        self.logger.warning(
                            "Flow run is no longer in a running state; the current state is: %r",
                            flow_run_info.state,
                        )
                    if isinstance(flow_run_info.state, Cancelling):
                        self.logger.info(
                            "Flow run has been cancelled, cancelling active tasks"
                        )
                        nonlocal cancelling
                        nonlocal flow_run_version
                        cancelling = True
                        flow_run_version = flow_run_info.version
                        # If not already leaving context, raise KeyboardInterrupt in the main thread
                        if not exiting_context:
                            if hasattr(signal, "raise_signal"):
                                # New in python 3.8
                                signal.raise_signal(
                                    signal.SIGINT)  # type: ignore
                            else:
                                if os.name == "nt":
                                    # This doesn't actually send a signal, so it will only
                                    # interrupt the next Python bytecode instruction - if the
                                    # main thread is blocked in a c extension the interrupt
                                    # won't be seen until that returns.
                                    from _thread import interrupt_main

                                    interrupt_main()
                                else:
                                    signal.pthread_kill(
                                        threading.main_thread().ident,
                                        signal.SIGINT  # type: ignore
                                    )
                        break
                    elif exiting_context:
                        break
Exemplo n.º 21
0
 def command_line_interface(self):
     "Método que lee instrucciones desde la línea de comandos"
     while True:
         try:
             text = input()
         except EOFError:
             signal.pthread_kill(threading.main_thread().ident, signal.SIGTERM)
             return
         splitted = text.split(' ')
         if len(splitted) == 1:
             self.command_handler(splitted[0], None)
         elif len(splitted) > 1:
             self.command_handler(splitted[0], splitted[1])
Exemplo n.º 22
0
 def interruption():
     nonlocal message
     if message is None:
         desc = 'current' if ident is None else 'main' if ident == 0 else self.ident
         message = "Interrupting {} {} after {}s timeout.".format(interrupt, desc, timeout_secs)
     log.log(log_level, message)
     if before_interrupt is not None:
         before_interrupt()
     if interrupt == 'thread':
         # _thread.interrupt_main()
         signal.pthread_kill(self.ident, sig)
     elif interrupt == 'process':
         os.kill(self.ident, sig)
Exemplo n.º 23
0
 def move(self, event, task):
     if event.direction == 'enter' and self.position[0] == 1:
         task.ctrl_queue.send_pyobj(['QUIT'])
     if event.direction == 'enter':
         signal.pthread_kill(main_thread().ident, signal.SIGINT)
     delta = super().move(event, task)
     if event.direction == 'up':
         task.renderer = self.main
         task.transition = partial(
             task.screen.slide_to, direction='down', duration=0.5)
     elif delta != (0, 0):
         self.update_text()
         task.transition = partial(
             task.screen.slide_to,
             direction='left' if delta == (1, 0) else 'right', duration=0.5)
     return delta
Exemplo n.º 24
0
            def handler(self, signum, frame):
                self.release()
                self.interrupted = True

                print("\nCTRL+C has been catched... Shutting down server...")

                if tcpserver.tcp_server:
                    tcpserver.tcp_server.shutdown()
                    tcpserver.tcp_server.server_close()
                    tcpserver.tcp_server = None

                if tcpserver.tcp_server_thread:
                    # print(tcpserver.tcp_server_thread.is_alive())
                    tcpserver.tcp_server_thread = None

                signal.pthread_kill(threading.get_ident(), signal.SIGTERM)
Exemplo n.º 25
0
def test_config_reading():
    """Test reading the config."""
    with NamedTemporaryFile('w', delete=False) as the_file:
        fname = the_file.name
        try:
            with patch.object(YAMLConfig, 'read_config') as rc:
                assert rc.call_count == 0
                yconf = YAMLConfig(fname)
                time.sleep(.1)
                assert rc.call_count == 1
                the_file.write(test_yaml1)
                the_file.flush()
                the_file.close()
                time.sleep(.1)
                assert rc.call_count == 2
                signal.pthread_kill(get_ident(), signal.SIGUSR1)
                time.sleep(.1)
                assert rc.call_count == 3
                os.remove(fname)
                signal.pthread_kill(get_ident(), signal.SIGUSR1)
                time.sleep(.1)
                yconf.close()
        finally:
            yconf.close()
            try:
                os.remove(fname)
            except FileNotFoundError:
                pass

    expected = yaml.safe_load(test_yaml1)
    with NamedTemporaryFile('w', delete=False) as the_file:
        fname = the_file.name
        try:
            yconf = YAMLConfig(fname)
            time.sleep(.1)
            the_file.write(test_yaml1)
            the_file.flush()
            the_file.close()
            time.sleep(.1)
            assert yconf.config == expected
        finally:
            yconf.close()
            try:
                os.remove(fname)
            except FileNotFoundError:
                pass
Exemplo n.º 26
0
 def move(self, event, task):
     x, y = self.position
     if event.direction == 'enter':
         if x == 1:
             subprocess.call(['sudo', '-n', 'reboot'])
         elif x == 2:
             subprocess.call(['sudo', '-n', 'poweroff'])
         signal.pthread_kill(main_thread().ident, signal.SIGINT)
     delta = super().move(event, task)
     if event.direction == 'up':
         task.switch_to(task.renderers['main'],
                        transition='slide',
                        direction='down',
                        duration=0.5)
     elif delta != (0, 0):
         self.update_text()
     return delta
Exemplo n.º 27
0
 def update_devices(self):
     devices = self.enumerate_keyboard_event_devices()
     with self._map_lock:
         for device in self._map.keys():
             if device not in devices:
                 if self._map[device].is_alive():
                     signal.pthread_kill(self._map[device].get_native_id(), signal.SIGKILL)
                     self._map[device].join()
                     del self._map[device]
                     if is_verbose:
                         print(f'Killed Alt+Shift Thread for {device}')
                         show_threads()
         for device in devices:
             if device not in self._map:
                 thread = self._map[device] = AltShiftNotify(device, self)
                 thread.start()
                 if is_verbose:
                     print(f'Started Alt+Shift Thread for {device}')
                     show_threads()
Exemplo n.º 28
0
    def commit(self):
        """
        Multicast the result of the current node

        :return: result
        """
        result = self.valid_block()

        if result:
            self.status[3][0].add(self.node_identifier)
        else:
            self.status[3][1].add(self.node_identifier)

        data = {
            'result': result,
            'phase': 2,
            'index': self.current_block.get('index')
        }

        sign = rsa.sign(str(data).encode('utf8'), self.prikey, 'SHA-1')
        headers = {'Connection': 'close', 'Content-Type': 'application/json'}

        web_chain_len = len(self.chain)
        for node in self.nodes:
            url = 'http://' + self.nodes[node][0] + '/consensus'  # idx 0 = addr
            print("commit: from", self.node_identifier, "to", url)
            cdata = rsa.encrypt(str(data).encode('utf8'),
                                self.nodes[node][1])  # idx 1 = pubkey
            fdata = {
                'data': list(cdata),
                'sign': list(sign),
                'id': self.node_identifier
            }
            jdata = json.dumps(fdata)

            threading.Thread(target=self.block_thread,
                             args=(url, headers, jdata)).start()
            self.send2web(web_chain_len, 2, node, str(data['result']))

        self.is_block = False
        print("commit thread_id : " + str(self.thread_id))
        signal.pthread_kill(self.thread_id, signal.SIGUSR1)
        return result
Exemplo n.º 29
0
async def test_keyboard_interrupt_teardown():
    asyncio_loop_closed = trio.Event()

    async def work_in_trio_no_matter_what(*,
                                          task_status=trio.TASK_STATUS_IGNORED
                                          ):
        await trio_asyncio.aio_as_trio(work_in_asyncio)()
        try:
            # KeyboardInterrupt won't cancel this coroutine thanks to the shield
            with trio.CancelScope(shield=True):
                task_status.started()
                await asyncio_loop_closed.wait()
        finally:
            # Hence this call will be exceuted after run_asyncio_loop is cancelled
            with pytest.raises(RuntimeError):
                await trio_asyncio.aio_as_trio(work_in_asyncio)()

    async def work_in_asyncio():
        await asyncio.sleep(0)

    async def run_asyncio_loop(nursery,
                               *,
                               task_status=trio.TASK_STATUS_IGNORED):
        with trio.CancelScope() as cancel_scope:
            try:
                async with trio_asyncio.open_loop():
                    # Starting a coroutine from here make it inherit the access
                    # to the asyncio loop context manager
                    await nursery.start(work_in_trio_no_matter_what)
                    task_status.started(cancel_scope)
                    await trio.sleep_forever()
            finally:
                asyncio_loop_closed.set()

    import signal
    import threading
    with pytest.raises(KeyboardInterrupt):
        with pytest.warns(RuntimeWarning):
            async with trio.open_nursery() as nursery:
                await nursery.start(run_asyncio_loop, nursery)
                # Trigger KeyboardInterrupt that should propagate accross the coroutines
                signal.pthread_kill(threading.get_ident(), signal.SIGINT)
Exemplo n.º 30
0
def kill_sender_reciever(thread1, thread2=None):
    '''
    kill sender reciever and TorrentDHT socket when there is
    continuous bootstrap.
    '''
    identification = thread1.ident
    try:
        signal.pthread_kill(identification, 2)
    except ProcessLookupError:
        pass

    # take some time to kill reciever thread
    if thread2 is None:
        return

    identification = thread2.ident
    try:
        signal.pthread_kill(identification, 2)
    except ProcessLookupError:
        pass
Exemplo n.º 31
0
    def on_key_press(self, symbol: int, modifiers: int):

        # Just kill the program I don't care how
        if symbol == Keymap.Esc.value:
            arcade.close_window()
            signal.pthread_kill(threading.current_thread().ident,
                                signal.SIGKILL)

        # Forward
        if symbol == Keymap.W.value:
            self.movement_values[0] = True

        if symbol == Keymap.Up.value:
            self.movement_values[1] = True

        # Reverse
        if symbol == Keymap.S.value:
            self.movement_values[2] = True

        if symbol == Keymap.Down.value:
            self.movement_values[3] = True
Exemplo n.º 32
0
 def interruption():
     log.log(log_level, self.message)
     if before_interrupt is not None:
         before_interrupt()
     while not self.interrupt_event.is_set():
         try:
             if interrupt == 'thread':
                 if isinstance(self.sig, (type(None), BaseException)):
                     exc = TimeoutError(
                         self.message) if self.sig is None else self.sig
                     raise_in_thread(self.ident, exc)
                 else:
                     # _thread.interrupt_main()
                     signal.pthread_kill(self.ident, self.sig)
             elif interrupt == 'process':
                 os.kill(self.ident, self.sig)
         except Exception:
             raise
         finally:
             self.interrupt_event.wait(
                 1)  # retry every second if interruption didn't work
Exemplo n.º 33
0
    def closeEvent(self, event):
        # Call Parent (QMainWindow).close()
        super(MainWindow, self).closeEvent(event)

        print(self.t_child_saveImages.ident)
        print(self.t_child_runServer.ident)
        print(self.t_grandchild_list)

        # Afterwards Process - Removal of Files
        shutil.rmtree('./S_CameraVision/Images')
        os.mkdir('./S_CameraVision/Images')

        shutil.rmtree('./S_CameraVision/Images_Box/Filtered')
        os.mkdir('./S_CameraVision/Images_Box/Filtered')

        shutil.rmtree('./S_CameraVision/Images_Box/Robot')
        os.mkdir('./S_CameraVision/Images_Box/Robot')

        shutil.rmtree('./S_CameraVision/Images_Box/Sticker')
        os.mkdir('./S_CameraVision/Images_Box/Sticker')

        # Afterwards Process - Killing normal threads
        for t_grandchild in self.t_grandchild_list:
            signal.pthread_kill(t_grandchild.ident, signal.SIGKILL)

        # TODO: Unreached... Why?
        signal.pthread_kill(self.t_child_saveImages.ident, signal.SIGKILL)
        signal.pthread_kill(self.t_child_runServer.ident, signal.SIGKILL)
Exemplo n.º 34
0
	def update_wakeup_handler(self, ev=None, disconnected=False):
		if disconnected:
			self.connected = False
			signal.pthread_kill(threading.main_thread().ident, signal.SIGWINCH)
		elif self.connected is None: self.connected = True
		self._updates.append(ev)
Exemplo n.º 35
0
def handle_sigint(sig, frame):
    for thread in threads:
        signal.pthread_kill(thread.ident, signal.SIGINT)

    sys.exit(0)
Exemplo n.º 36
0
import time
def countdown(n):
    while n > 0: 
        print('T-minus', n) 
        n -= 1 
        time.sleep(1)

from threading import Thread
import threading
import signal
# t = Thread(target=countdown, args=(5,)) 
# t.start()
# t.join()
# print "ok"

# threads = [Thread(target=countdown, args=(i,)) for i in range(3,5)]
# [t.start() for t in threads]
# [t.join() for t in threads]
# print "ok"

threading.get_ident()
aa = Thread(target=countdown, args=(30,))
aa.start()
aa.ident
signal.pthread_kill(aa.ident, 1)
aa.is_alive()
print("ok")
Exemplo n.º 37
0
 def interrupt_main():
     signal.pthread_kill(main_thread, signal.SIGINT)
Exemplo n.º 38
0
 def run(self):
     game.run()
     signal.pthread_kill(main_thread_id, signal.SIGQUIT)
Exemplo n.º 39
0
 def signal_raise(signum):
     # Use pthread_kill to make sure we're actually using the wakeup fd on
     # Unix
     signal.pthread_kill(threading.get_ident(), signum)