Python signal.SIG_IGN Examples

The following are 30 code examples for showing how to use signal.SIG_IGN(). 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: jawfish   Author: war-and-code   File: signals.py    License: MIT License 6 votes vote down vote up
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler 
Example 2
Project: cloudml-samples   Author: GoogleCloudPlatform   File: data-extractor.py    License: Apache License 2.0 6 votes vote down vote up
def parallel_map(function, iterable):
  """Calls a function for every element in an iterable using multiple cores."""
  if FORCE_DISABLE_MULTIPROCESSING:
    return [function(*args) for args in iterable]

  original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
  num_threads = mp.cpu_count() * 2
  pool = mp.Pool(processes=num_threads)
  signal.signal(signal.SIGINT, original_sigint_handler)

  p = pool.map_async(_function_wrapper, ((function, args) for args in iterable))
  try:
    results = p.get(0xFFFFFFFF)
  except KeyboardInterrupt:
    pool.terminate()
    raise
  pool.close()
  return results 
Example 3
Project: ReadableWebProxy   Author: fake-name   File: UrlUpserter.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, msg_queue, db_interface):
		self.response_queue = msg_queue
		self.log = logging.getLogger("Main.LinkAggregator")

		try:
			signal.signal(signal.SIGINT, signal.SIG_IGN)
		except ValueError:
			self.log.warning("Cannot configure job fetcher task to ignore SIGINT. May be an issue.")

		# LRU Cache with a maxsize of 1 million, and a TTL of 6 hours
		self.seen = cachetools.TTLCache(maxsize=1000 * 1000, ttl=60 * 60 * 6)

		self.queue_items = 0
		self.link_count = 0
		self.amqpUpdateCount = 0
		self.deathCounter = 0

		self.batched_links = []
		self.pending_upserts = []

		self.db_int = db_interface
		self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=6)

		self.check_init_func() 
Example 4
Project: ironpython2   Author: IronLanguages   File: signals.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, (int, long)):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler 
Example 5
Project: ironpython2   Author: IronLanguages   File: test_break.py    License: Apache License 2.0 6 votes vote down vote up
def testSecondInterrupt(self):
        # Can't use skipIf decorator because the signal handler may have
        # been changed after defining this method.
        if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
            self.skipTest("test requires SIGINT to not be ignored")
        result = unittest.TestResult()
        unittest.installHandler()
        unittest.registerResult(result)

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
            result.breakCaught = True
            self.assertTrue(result.shouldStop)
            os.kill(pid, signal.SIGINT)
            self.fail("Second KeyboardInterrupt not raised")

        try:
            test(result)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("Second KeyboardInterrupt not raised")
        self.assertTrue(result.breakCaught) 
Example 6
Project: ironpython2   Author: IronLanguages   File: test_break.py    License: Apache License 2.0 6 votes vote down vote up
def testHandlerReplacedButCalled(self):
        # Can't use skipIf decorator because the signal handler may have
        # been changed after defining this method.
        if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
            self.skipTest("test requires SIGINT to not be ignored")
        # If our handler has been replaced (is no longer installed) but is
        # called by the *new* handler, then it isn't safe to delay the
        # SIGINT and we should immediately delegate to the default handler
        unittest.installHandler()

        handler = signal.getsignal(signal.SIGINT)
        def new_handler(frame, signum):
            handler(frame, signum)
        signal.signal(signal.SIGINT, new_handler)

        try:
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("replaced but delegated handler doesn't raise interrupt") 
Example 7
Project: locality-sensitive-hashing   Author: singhj   File: multiprocess.py    License: MIT License 6 votes vote down vote up
def _import_mp():
    global Process, Queue, Pool, Event, Value, Array
    try:
        from multiprocessing import Manager, Process
        #prevent the server process created in the manager which holds Python 
        #objects and allows other processes to manipulate them using proxies
        #to interrupt on SIGINT (keyboardinterrupt) so that the communication
        #channel between subprocesses and main process is still usable after
        #ctrl+C is received in the main process.
        old=signal.signal(signal.SIGINT, signal.SIG_IGN)
        m = Manager()
        #reset it back so main process will receive a KeyboardInterrupt
        #exception on ctrl+c
        signal.signal(signal.SIGINT, old)
        Queue, Pool, Event, Value, Array = (
                m.Queue, m.Pool, m.Event, m.Value, m.Array
        )
    except ImportError:
        warn("multiprocessing module is not available, multiprocess plugin "
             "cannot be used", RuntimeWarning) 
Example 8
Project: octavia   Author: openstack   File: driver_agent.py    License: Apache License 2.0 6 votes vote down vote up
def _process_wrapper(exit_event, proc_name, function, agent_name=None):
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    signal.signal(signal.SIGHUP, _mutate_config)
    if agent_name:
        process_title = 'octavia-driver-agent - {} -- {}'.format(
            proc_name, agent_name)
    else:
        process_title = 'octavia-driver-agent - {}'.format(proc_name)
    setproctitle.setproctitle(process_title)
    while not exit_event.is_set():
        try:
            function(exit_event)
        except Exception as e:
            if agent_name:
                LOG.exception('Provider agent "%s" raised exception: %s. '
                              'Restarting the "%s" provider agent.',
                              agent_name, str(e), agent_name)
            else:
                LOG.exception('%s raised exception: %s. '
                              'Restarting %s.',
                              proc_name, str(e), proc_name)
            time.sleep(1)
            continue
        break 
Example 9
Project: reconchess   Author: reconnaissanceblindchess   File: rc_connect.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def accept_invitation_and_play(server_url, auth, invitation_id, bot_cls, finished):
    # make sure this process doesn't react to interrupt signals
    signal.signal(signal.SIGTERM, signal.SIG_IGN)
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    print('[{}] Accepting invitation {}.'.format(datetime.now(), invitation_id))

    server = RBCServer(server_url, auth)
    game_id = server.accept_invitation(invitation_id)

    print('[{}] Invitation {} accepted. Playing game {}.'.format(datetime.now(), invitation_id, game_id))

    try:
        play_remote_game(server_url, game_id, auth, bot_cls())
        print('[{}] Finished game {}'.format(datetime.now(), game_id))
    except:
        print('[{}] Fatal error in game {}:'.format(datetime.now(), game_id))
        traceback.print_exc()
        server.error_resign(game_id)
    finally:
        server.finish_invitation(invitation_id)
        finished.value = True 
Example 10
Project: BinderFilter   Author: dxwu   File: signals.py    License: MIT License 6 votes vote down vote up
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler 
Example 11
Project: BinderFilter   Author: dxwu   File: test_break.py    License: MIT License 6 votes vote down vote up
def testSecondInterrupt(self):
        # Can't use skipIf decorator because the signal handler may have
        # been changed after defining this method.
        if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
            self.skipTest("test requires SIGINT to not be ignored")
        result = unittest.TestResult()
        unittest.installHandler()
        unittest.registerResult(result)

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
            result.breakCaught = True
            self.assertTrue(result.shouldStop)
            os.kill(pid, signal.SIGINT)
            self.fail("Second KeyboardInterrupt not raised")

        try:
            test(result)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("Second KeyboardInterrupt not raised")
        self.assertTrue(result.breakCaught) 
Example 12
Project: BinderFilter   Author: dxwu   File: test_break.py    License: MIT License 6 votes vote down vote up
def testHandlerReplacedButCalled(self):
        # Can't use skipIf decorator because the signal handler may have
        # been changed after defining this method.
        if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
            self.skipTest("test requires SIGINT to not be ignored")
        # If our handler has been replaced (is no longer installed) but is
        # called by the *new* handler, then it isn't safe to delay the
        # SIGINT and we should immediately delegate to the default handler
        unittest.installHandler()

        handler = signal.getsignal(signal.SIGINT)
        def new_handler(frame, signum):
            handler(frame, signum)
        signal.signal(signal.SIGINT, new_handler)

        try:
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("replaced but delegated handler doesn't raise interrupt") 
Example 13
Project: Computable   Author: ktraunmueller   File: multiprocess.py    License: MIT License 6 votes vote down vote up
def _import_mp():
    global Process, Queue, Pool, Event, Value, Array
    try:
        from multiprocessing import Manager, Process
        #prevent the server process created in the manager which holds Python 
        #objects and allows other processes to manipulate them using proxies
        #to interrupt on SIGINT (keyboardinterrupt) so that the communication
        #channel between subprocesses and main process is still usable after
        #ctrl+C is received in the main process.
        old=signal.signal(signal.SIGINT, signal.SIG_IGN)
        m = Manager()
        #reset it back so main process will receive a KeyboardInterrupt
        #exception on ctrl+c
        signal.signal(signal.SIGINT, old)
        Queue, Pool, Event, Value, Array = (
                m.Queue, m.Pool, m.Event, m.Value, m.Array
        )
    except ImportError:
        warn("multiprocessing module is not available, multiprocess plugin "
             "cannot be used", RuntimeWarning) 
Example 14
Project: mongodb_consistent_backup   Author: Percona-Lab   File: Task.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, task_name, manager, config, timer, base_dir, backup_dir, **kwargs):
        self.task_name  = task_name
        self.manager    = manager
        self.config     = config
        self.timer      = timer
        self.base_dir   = base_dir
        self.backup_dir = backup_dir
        self.args       = kwargs
        self.verbose    = self.config.verbose

        self.runnning  = False
        self.stopped   = False
        self.completed = False
        self.exit_code = 255

        self.thread_count          = None
        self.cpu_count             = cpu_count()
        self.compression_method    = 'none'
        self.compression_supported = ['none']
        self.timer_name            = self.__class__.__name__

        signal(SIGINT, SIG_IGN)
        signal(SIGTERM, self.close) 
Example 15
Project: oss-ftp   Author: aliyun   File: signals.py    License: MIT License 6 votes vote down vote up
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler 
Example 16
Project: oss-ftp   Author: aliyun   File: test_break.py    License: MIT License 6 votes vote down vote up
def testSecondInterrupt(self):
        # Can't use skipIf decorator because the signal handler may have
        # been changed after defining this method.
        if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
            self.skipTest("test requires SIGINT to not be ignored")
        result = unittest.TestResult()
        unittest.installHandler()
        unittest.registerResult(result)

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
            result.breakCaught = True
            self.assertTrue(result.shouldStop)
            os.kill(pid, signal.SIGINT)
            self.fail("Second KeyboardInterrupt not raised")

        try:
            test(result)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("Second KeyboardInterrupt not raised")
        self.assertTrue(result.breakCaught) 
Example 17
Project: oss-ftp   Author: aliyun   File: test_break.py    License: MIT License 6 votes vote down vote up
def testHandlerReplacedButCalled(self):
        # Can't use skipIf decorator because the signal handler may have
        # been changed after defining this method.
        if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
            self.skipTest("test requires SIGINT to not be ignored")
        # If our handler has been replaced (is no longer installed) but is
        # called by the *new* handler, then it isn't safe to delay the
        # SIGINT and we should immediately delegate to the default handler
        unittest.installHandler()

        handler = signal.getsignal(signal.SIGINT)
        def new_handler(frame, signum):
            handler(frame, signum)
        signal.signal(signal.SIGINT, new_handler)

        try:
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("replaced but delegated handler doesn't raise interrupt") 
Example 18
Project: Generative-ConvACs   Author: HUJI-Deep   File: model_analyzer.py    License: MIT License 6 votes vote down vote up
def init_worker(num_instances, kernel_h, kernel_w, pad, stride, indices, pdfs):
    global g_num_instances
    g_num_instances = num_instances
    global g_kernel_h
    g_kernel_h = kernel_h
    global g_kernel_w
    g_kernel_w = kernel_w
    global g_pad
    g_pad = pad
    global g_stride
    g_stride = stride
    global g_indices
    g_indices = indices
    global g_pdfs
    g_pdfs = pdfs
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    np.random.seed(None) 
Example 19
Project: incubator-spot   Author: apache   File: collector.py    License: Apache License 2.0 5 votes vote down vote up
def _init_child(tmpdir):
    '''
        Initialize new process from multiprocessing module's Pool.

    :param tmpdir: Path of local staging area.
    '''
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    # .................................for each process, create a isolated temp folder
    proc_dir = os.path.join(tmpdir, current_process().name)

    if not os.path.isdir(proc_dir):
        os.mkdir(proc_dir) 
Example 20
Project: sqliv   Author: the-robot   File: scanner.py    License: GNU General Public License v3.0 5 votes vote down vote up
def init():
    signal.signal(signal.SIGINT, signal.SIG_IGN) 
Example 21
Project: sqliv   Author: the-robot   File: serverinfo.py    License: GNU General Public License v3.0 5 votes vote down vote up
def init():
    signal.signal(signal.SIGINT, signal.SIG_IGN) 
Example 22
Project: rtp_cluster   Author: sippy   File: Signal.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def signal_handler(self, signum, *frame):
        ED2.callFromThread(self.dispatch)
        if self.previous_handler not in (SIG_IGN, SIG_DFL):
            try:
                self.previous_handler(signum, *frame)
            except:
                dump_exception('Signal: unhandled exception in signal chain') 
Example 23
Project: dataflow   Author: tensorpack   File: concurrency.py    License: Apache License 2.0 5 votes vote down vote up
def mask_sigint():
    """
    Returns:
        If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True.
        Otherwise yield False.
    """
    if is_main_thread():
        sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
        yield True
        signal.signal(signal.SIGINT, sigint_handler)
    else:
        yield False 
Example 24
Project: chainerrl   Author: chainer   File: multiprocess_vector_env.py    License: MIT License 5 votes vote down vote up
def worker(remote, env_fn):
    # Ignore CTRL+C in the worker process
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    env = env_fn()
    try:
        while True:
            cmd, data = remote.recv()
            if cmd == 'step':
                ob, reward, done, info = env.step(data)
                remote.send((ob, reward, done, info))
            elif cmd == 'reset':
                ob = env.reset()
                remote.send(ob)
            elif cmd == 'close':
                remote.close()
                break
            elif cmd == 'get_spaces':
                remote.send((env.action_space, env.observation_space))
            elif cmd == 'spec':
                remote.send(env.spec)
            elif cmd == 'seed':
                remote.send(env.seed(data))
            else:
                raise NotImplementedError
    finally:
        env.close() 
Example 25
Project: errand-boy   Author: greyside   File: base.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def worker_init(*args):
    name = multiprocessing.current_process().name
    logger.debug('Worker initialized: {}'.format(name))
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    setproctitle('errand-boy worker process {}'.format(name.split('-')[1])) 
Example 26
Project: zdict   Author: zdict   File: zdict.py    License: GNU General Public License v3.0 5 votes vote down vote up
def init_worker():
    # When -j been used, make subprocesses ignore KeyboardInterrupt
    # for not showing KeyboardInterrupt traceback error message.
    import signal
    signal.signal(signal.SIGINT, signal.SIG_IGN) 
Example 27
Project: gipc   Author: jgehrcke   File: infinite_send_to_child.py    License: MIT License 5 votes vote down vote up
def initiate_shutdown(_, __):
    """
    I think three aspects are noteworthy of this function:

    1) When the handler for a particular signal is invoked, that signal is
       automatically blocked until the handler returns. That means that if two
       signals of the same kind, SIGINT in this case, arrive close together, the
       second one will be held until the first has been handled.

    2) The set of actions that can safely be performed within a signal handler
       is small. On Linux it is safe to call `signal()` (see
       http://man7.org/linux/man-pages/man7/signal-safety.7.html) to install a
       different signal handler but notably as of the CERT C Coding Standard,
       rule SIG30-C, `signal()` is one of the only four C standard library
       functions which can safely be called from within a signal handler.

    3) For educational purposes it would be good to `print()` here (as I have
       done in the rest of the program) so that the control flow is obvious from
       the program output. However, then the program sould not be correct
       anymore: Python's IO system is not reentrant
       (https://bugs.python.org/issue24283).
    """
    # Let the program know that it should initiate the shutdown procedure.
    global shutdown
    shutdown = True

    # Ignore subsequent SIGINTs.
    signal.signal(signal.SIGINT, signal.SIG_IGN) 
Example 28
Project: gipc   Author: jgehrcke   File: infinite_send_to_child.py    License: MIT License 5 votes vote down vote up
def child_process(reader):
    """
    Ignore SIGINT (default handler in CPython is to raise KeyboardInterrupt,
    which is undesired here). The parent handles it, and instructs the child to
    clean up as part of handling it.
    """
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    while True:
        print("Child process got message through pipe:\n\t'%s'" % reader.get()) 
Example 29
Project: linter-pylama   Author: AtomLinter   File: checker.py    License: MIT License 5 votes vote down vote up
def _pool_init():
    """Ensure correct signaling of ^C using multiprocessing.Pool."""
    signal.signal(signal.SIGINT, signal.SIG_IGN) 
Example 30
Project: ffw   Author: dobin   File: honggmaster.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _fuzzWithFork(self, q):
        # have to remove sigint handler before forking children
        # so ctlr-c works
        orig = signal.signal(signal.SIGINT, signal.SIG_IGN)

        procs = []
        n = 0

        # prepare data structure
        while n < self.config["processes"]:
            print("Start fuzzing child #" + str(n))
            r = random.randint(0, 2**32 - 1)

            proc = {
                "r": r,
                "q": q,
                "config": self.config,
                "n": n,
                "p": None,
            }
            procs.append(proc)
            n += 1

        # start processes
        for proc in procs:
            self._startThread(proc)

        self.state = FuzzerState.WARMUP

        # restore signal handler
        signal.signal(signal.SIGINT, orig)

        self._fuzzConsole(q, procs)