当前位置: 首页>>代码示例>>Python>>正文


Python signal.siginterrupt函数代码示例

本文整理汇总了Python中signal.siginterrupt函数的典型用法代码示例。如果您正苦于以下问题:Python siginterrupt函数的具体用法?Python siginterrupt怎么用?Python siginterrupt使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了siginterrupt函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _child_handler

 def _child_handler(self, sig, stack):
     pid, sts = os.waitpid(-1, os.WNOHANG)
     proc = self._procs.get(pid)
     if proc is not None:
         self._proc_status(proc, sts)
     signal.signal(SIGCHLD, self._child_handler)
     signal.siginterrupt(SIGCHLD, False)
开发者ID:kdart,项目名称:pycopia3,代码行数:7,代码来源:proctools.py

示例2: init_signals

    def init_signals(self):
        # reset signal handlers to defaults
        [signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS]

        # einhorn will send SIGUSR2 to request a graceful shutdown
        signal.signal(signal.SIGUSR2, self.start_graceful_shutdown)
        signal.siginterrupt(signal.SIGUSR2, False)
开发者ID:AHAMED750,项目名称:reddit,代码行数:7,代码来源:einhorn.py

示例3: add_signal_handler

    def add_signal_handler(self, sig, callback, *args):
        """Add a handler for a signal.  UNIX only.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        """
        self._check_signal(sig)
        try:
            # set_wakeup_fd() raises ValueError if this is not the
            # main thread.  By calling it early we ensure that an
            # event loop running in another thread cannot add a signal
            # handler.
            signal.set_wakeup_fd(self._csock.fileno())
        except ValueError as exc:
            raise RuntimeError(str(exc))

        handle = events.make_handle(callback, args)
        self._signal_handlers[sig] = handle

        try:
            signal.signal(sig, self._handle_signal)
            # Set SA_RESTART to limit EINTR occurrences.
            signal.siginterrupt(sig, False)
        except OSError as exc:
            del self._signal_handlers[sig]
            if not self._signal_handlers:
                try:
                    signal.set_wakeup_fd(-1)
                except ValueError as nexc:
                    logger.info('set_wakeup_fd(-1) failed: %s', nexc)

            if exc.errno == errno.EINVAL:
                raise RuntimeError('sig {} cannot be caught'.format(sig))
            else:
                raise
开发者ID:ProDataLab,项目名称:cpython,代码行数:35,代码来源:unix_events.py

示例4: open

    def open(self):
        """
        Fork a child nethack process into a pty and setup its stdin and stdout
        """

        (self.pid, self.pipe) = os.forkpty()

        if self.pid == 0:
            # I'm the child process in a fake pty. I need to replace myself
            # with an instance of nethack.
            #
            # NOTE: The '--proxy' argument doesn't seem to do anything though
            # it's used by dgamelaunch which is a bit confusing. However, 
            # without *some* argument execvp doesn't seem to like nethack and
            # launches a shell instead? It's quite confusing.
            if self.debug:
                os.execvpe("nethack", ["--proxy", "-D"], os.environ)
            else:
                os.execvpe("nethack", ["--proxy"], os.environ)
        else:
            # Before we do anything else, it's time to establish some boundries
            signal.siginterrupt(signal.SIGCHLD, True)
            signal.signal(signal.SIGCHLD, self._close)

            # When my tty resizes, the child's pty should resize too.
            signal.signal(signal.SIGWINCH, self.resize_child)

            # Setup out input/output proxies
            self.stdout = os.fdopen(self.pipe, "rb", 0)
            self.stdin = os.fdopen(self.pipe, "wb", 0)

            # Set the initial size of the child pty to my own size.
            self.resize_child()
开发者ID:Biddilets,项目名称:noobhack,代码行数:33,代码来源:process.py

示例5: main

def main():
    """Parses the arguments and call worker()"""
    # Set the signal handler
    for s in [signal.SIGINT, signal.SIGTERM]:
        signal.signal(s, shutdown)
        signal.siginterrupt(s, False)
    parser, _ = utils.create_argparser(__doc__)
    parser.add_argument(
        '--sensor', metavar='SENSOR[:SENSOR]',
        help='sensor to check, optionally with a long name, defaults to all.',
    )
    parser.add_argument(
        '--directory', metavar='DIR',
        help='base directory (defaults to /ivre/passiverecon/).',
        default="/ivre/passiverecon/",
    )
    parser.add_argument(
        '--progname', metavar='PROG',
        help='Program to run (defaults to ivre passiverecon2db).',
        default="ivre passiverecon2db",
    )
    args = parser.parse_args()
    if args.sensor is not None:
        SENSORS.update(dict([args.sensor.split(':', 1)
                             if ':' in args.sensor
                             else [args.sensor, args.sensor]]))
        sensor = args.sensor.split(':', 1)[0]
    else:
        sensor = None
    worker(args.progname, args.directory, sensor=sensor)
开发者ID:CyrilleFranchet,项目名称:ivre,代码行数:30,代码来源:passivereconworker.py

示例6: __register_sighandler

 def __register_sighandler(self):
     # Register a SIGUSR1 handler.
     def handler(signum, frame):
         Ping.set(True)
     signal.signal(signal.SIGUSR1, handler)
     # Don't interrupt system cals on SIGUSR1.
     signal.siginterrupt(signal.SIGUSR1, False)
开发者ID:maarons,项目名称:Shade,代码行数:7,代码来源:PaControl.py

示例7: daemonize

def daemonize(do_fork=True, skip_fds=[]):
    """Daemonizes current process."""

    if do_fork:
        if os.fork():
            os._exit(0)
        else:
            os.setsid()

            if os.fork():
                os._exit(0)

    os.chdir("/")
    os.umask(0)

    signal.signal(signal.SIGHUP, signal.SIG_IGN)
    signal.siginterrupt(signal.SIGHUP, False)

    # Redirecting standard streams to /dev/null and closing original descriptors
    null_dev = eintr_retry(os.open)("/dev/null", os.O_RDWR)
    try:
        for fd in (sys.stdin.fileno(), sys.stdout.fileno(), sys.stderr.fileno()):
            if fd not in skip_fds:
                os.dup2(null_dev, fd)
    finally:
        eintr_retry(os.close)(null_dev)
开发者ID:KonishchevDmitry,项目名称:psys,代码行数:26,代码来源:daemon.py

示例8: server_config

def server_config():
    global log_file, log_buffer 
    global data_fd, data_fifo
    #SIGINT clean up and quit
    signal.signal(signal.SIGINT, sigint_handler) 
    #keep alive timer
    signal.signal(signal.SIGALRM, sigtimer_handler)
    signal.setitimer(signal.ITIMER_REAL, KEEP_ALIVE, KEEP_ALIVE)
    #syscall interrupt: restart 
    signal.siginterrupt(signal.SIGALRM, False)
    signal.siginterrupt(signal.SIGUSR1, False)
    #server status
    signal.signal(signal.SIGUSR1, sigusr1_handler)
    #data channel
    data_fifo = "nonblocking_pid_%d.fifo" % os.getpid()
    os.mkfifo(data_fifo , 0666) 
    f = open(data_fifo, "r+")
    data_fd = os.dup(f.fileno())
    f.close()
    #main log
    if os.path.exists(NONBLOCKING_LOG): 
        log_file = open(NONBLOCKING_LOG, "a+")
    else:
        log_file = open(NONBLOCKING_LOG, "w")
    if LOG_BUFFER_SIZE:
        log_buffer = StringIO()
开发者ID:LOLOriana,项目名称:ac-rss,代码行数:26,代码来源:nonblocking.py

示例9: reset_signal_handler

  def reset_signal_handler(cls, signal_handler):
    """
    Class state:
    - Overwrites `cls._signal_handler`.
    OS state:
    - Overwrites signal handlers for SIGINT, SIGQUIT, and SIGTERM.

    NB: This method calls signal.signal(), which will crash if not called from the main thread!

    :returns: The :class:`SignalHandler` that was previously registered, or None if this is
              the first time this method was called.
    """
    assert(isinstance(signal_handler, SignalHandler))
    # NB: Modify process-global state!
    for signum, handler in signal_handler.signal_handler_mapping.items():
      signal.signal(signum, handler)
      # Retry any system calls interrupted by any of the signals we just installed handlers for
      # (instead of having them raise EINTR). siginterrupt(3) says this is the default behavior on
      # Linux and OSX.
      signal.siginterrupt(signum, False)

    previous_signal_handler = cls._signal_handler
    # NB: Mutate the class variables!
    cls._signal_handler = signal_handler
    return previous_signal_handler
开发者ID:jsirois,项目名称:pants,代码行数:25,代码来源:exception_sink.py

示例10: __init__

    def __init__(self):
        self.processes = {}

        # Stop all processes as last part of mainloop termination.
        main.signals['shutdown-after'].connect(self.stopall)
        main.signals['unix-signal'].connect(self._sigchld_handler)

        # Set SA_RESTART bit for the signal, which restarts any interrupted
        # system calls -- however, select (at least on Linux) is NOT restarted
        # for reasons described at:
        #    http://lkml.indiana.edu/hypermail/linux/kernel/0003.2/0336.html
        #
        # We do this early (which is effectively at import time, because
        # _Supervisor() gets instantiated at import) so that child processes
        # can be created before the main loop is started, and their
        # termination won't interrupt any system calls.
        if sys.hexversion >= 0x02060000:
            # Python 2.6+ has signal.siginterrupt()
            signal.siginterrupt(signal.SIGCHLD, False)
        elif sys.hexversion >= 0x02050000:
            # Python 2.5
            import ctypes, ctypes.util
            libc = ctypes.util.find_library('c')
            ctypes.CDLL(libc).siginterrupt(signal.SIGCHLD, 0)
        else:
            # Python 2.4- is not supported.
            raise SystemError('kaa.base requires Python 2.5 or later')
开发者ID:clones,项目名称:kaa,代码行数:27,代码来源:process.py

示例11: stop

    def stop(self, signum=None, _unused=None):
        """Stop the consumer from consuming by calling BasicCancel and setting
        our state.

        :param int signum: The signal received
        :param frame _unused: The stack frame from when the signal was called

        """
        LOGGER.debug('Stop called in state: %s', self.state_description)
        if self.is_stopped:
            LOGGER.warning('Stop requested but consumer is already stopped')
            return
        elif self.is_shutting_down:
            LOGGER.warning('Stop requested, consumer is already shutting down')
            return
        elif self.is_waiting_to_shutdown:
            LOGGER.warning('Stop requested but already waiting to shut down')
            return

        # Stop consuming and close AMQP connections
        self.shutdown_connections()

        # Wait until the consumer has finished processing to shutdown
        if self.is_processing:
            LOGGER.info('Waiting for consumer to finish processing')
            self.set_state(self.STATE_STOP_REQUESTED)
            if signum == signal.SIGTERM:
                signal.siginterrupt(signal.SIGTERM, False)
            return
开发者ID:gmr,项目名称:rejected,代码行数:29,代码来源:process.py

示例12: add_signal_handler

    def add_signal_handler(self, sig, callback, *args):
        """Add a handler for a signal.  UNIX only.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        """
        if (coroutines.iscoroutine(callback)
        or coroutines.iscoroutinefunction(callback)):
            raise TypeError("coroutines cannot be used "
                            "with add_signal_handler()")
        self._check_signal(sig)
        self._check_closed()
        try:
            # set_wakeup_fd() raises ValueError if this is not the
            # main thread.  By calling it early we ensure that an
            # event loop running in another thread cannot add a signal
            # handler.
            signal.set_wakeup_fd(self._csock.fileno())
        except (ValueError, OSError) as exc:
            raise RuntimeError(str(exc))

        handle = events.Handle(callback, args, self)
        self._signal_handlers[sig] = handle

        try:
            if compat.PY33:
                # On Python 3.3 and newer, the C signal handler writes the
                # signal number into the wakeup file descriptor and then calls
                # Py_AddPendingCall() to schedule the Python signal handler.
                #
                # Register a dummy signal handler to ask Python to write the
                # signal number into the wakup file descriptor.
                # _process_self_data() will read signal numbers from this file
                # descriptor to handle signals.
                signal.signal(sig, _sighandler_noop)
            else:
                # On Python 3.2 and older, the C signal handler first calls
                # Py_AddPendingCall() to schedule the Python signal handler,
                # and then write a null byte into the wakeup file descriptor.
                signal.signal(sig, self._handle_signal)

            # Set SA_RESTART to limit EINTR occurrences.
            signal.siginterrupt(sig, False)
        except (RuntimeError, OSError) as exc:
            # On Python 2, signal.signal(signal.SIGKILL, signal.SIG_IGN) raises
            # RuntimeError(22, 'Invalid argument'). On Python 3,
            # OSError(22, 'Invalid argument') is raised instead.
            exc_type, exc_value, tb = sys.exc_info()

            del self._signal_handlers[sig]
            if not self._signal_handlers:
                try:
                    signal.set_wakeup_fd(-1)
                except (ValueError, OSError) as nexc:
                    logger.info('set_wakeup_fd(-1) failed: %s', nexc)

            if isinstance(exc, RuntimeError) or exc.errno == errno.EINVAL:
                raise RuntimeError('sig {0} cannot be caught'.format(sig))
            else:
                reraise(exc_type, exc_value, tb)
开发者ID:bdrich,项目名称:neutron-lbaas,代码行数:60,代码来源:unix_events.py

示例13: sigusr1_handler

 def sigusr1_handler(self, signum, stack_frame):
     # Apparently the setting siginterrupt can get reset on some platforms.
     signal.siginterrupt(signal.SIGUSR1, False)
     print('Received SIGUSR1. Current stack trace:', file=sys.stderr)
     traceback.print_stack(stack_frame)
     if self.runner is not None:
         self.runner.debug_status()
开发者ID:WillChilds-Klein,项目名称:mistress-mapreduce,代码行数:7,代码来源:main.py

示例14: main

def main():
    signal.siginterrupt(signal.SIGINT, True)
    signal.signal(signal.SIGINT, exit)
    args = sys.argv
    if len(args) != 2 or args[1][-4:] == 'help':
        print("usage: python flashcard.py filename.json")
        sys.exit(0)

    with open(args[1], 'r') as f:
         text = f.read()
         d = json.loads(text)
         keys = list(d.keys())
         n = len(keys)
         while True:
             os.system('clear')
             print("Starting a new round")
             print("Press enter to proceed")
             input()
             for i in range(n):
                 target = random.randrange(i, n)
                 keys[i], keys[target] = keys[target], keys[i]
                 koi = keys[i]
                 os.system('clear')
                 print(koi)
                 input()
                 print(d[koi])
                 input()
开发者ID:ffanzhang,项目名称:myScripts,代码行数:27,代码来源:flashcard.py

示例15: init_signals

    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)
开发者ID:cr0hn,项目名称:aiohttp,代码行数:25,代码来源:worker.py


注:本文中的signal.siginterrupt函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。