• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python signal.siginterrupt函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: stop

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

        """
        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
        self.cancel_consumer_with_rabbitmq()

        # 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

        self.on_ready_to_stop()
开发者ID:petere,项目名称:rejected,代码行数:28,代码来源:process.py


示例17: main

def main():
    pipe_r, pipe_w = os.pipe()
    flags = fcntl.fcntl(pipe_w, fcntl.F_GETFL, 0)
    flags = flags | os.O_NONBLOCK
    fcntl.fcntl(pipe_w, fcntl.F_SETFL, flags)
    
    signal.signal(signal.SIGCHLD, lambda x,y: None)
    signal.signal(signal.SIGALRM, lambda x,y: None)
    signal.siginterrupt(signal.SIGCHLD,False) #makes no difference
    signal.siginterrupt(signal.SIGALRM,False) #makes no difference
    signal.set_wakeup_fd(pipe_w)
    signal.setitimer(signal.ITIMER_REAL, 2, 2)
    
    poller = select.epoll()
    poller.register(pipe_r, select.EPOLLIN)
    poller.register(sys.stdin, select.EPOLLIN)
    
    print "Main screen turn on"
    while True:
        events=[]
        try:
            events = poller.poll()
            try:
                for fd, flags in events:
                    ch=os.read(fd, 1)
                    if fd==pipe_r:
                        sys.stdout.write( "We get Signal" )
                    if fd==sys.stdin.fileno():
                        sys.stdout.write( ch )
                    sys.stdout.flush()
            except IOError as e:
                print "exception loop" + str(e)
        except IOError as e:
            print "exception poll" + str(e)
开发者ID:senseiafpa,项目名称:clonage_a_chaud,代码行数:34,代码来源:test-jo.py


示例18: fastingest

def fastingest(ns):
    """
    A really fast ingest version, unlike the
    echoprint server utility, which will eat all of you RAM.

    :param ns: Namespace object with required config
    :return: None
    """
    es = EchoprintServer(
        solr_url=ns.solr, tyrant_address=(ns.tyrant_host, ns.tyrant_port)
    )
    import_date = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")

    status = 0
    start_time = datetime.datetime.utcnow()

    def signal_handler(signum, frame):
        diff = datetime.datetime.utcnow() - start_time
        print '{0}, {1}'.format(diff, status)
    signal.signal(signal.SIGUSR1, signal_handler)
    signal.siginterrupt(signal.SIGUSR1, False)

    with committing(es), open(ns.path) as f:
        data = ijson.items(f, 'item')

        for item in data:
            song = Song.from_echoprint(item, import_date=import_date)
            if song is not None:
                # don't commit, the contextmanager (with) takes care of it
                es.ingest(song, commit=False,
                          check_duplicates=ns.check_duplicates)
            status += 1
开发者ID:Dav1dde,项目名称:emfas,代码行数:32,代码来源:__main__.py


示例19: main

def main(prog, args):
    listenfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)

    # empty string means INADDR_ANY
    servaddr = ('', const.SERV_PORT)

    listenfd.bind(servaddr)
    listenfd.listen(const.LISTENQ)

    signal.signal(signal.SIGCHLD, sig_chld)
    signal.siginterrupt(signal.SIGCHLD, False)

    while True:
        # XXX
        # In Python, socket.accept() is written in C so it will block
        # the main process from receiving the SIGCHLD signal
        # Thus the child process will remain in zombie status untill
        # next connection from client and this accept returns.
        #
        # By setting up timeout to listenfd and wrap accept in a loop is
        # a solution but not a perfect one.
        connfd, remote_addr = listenfd.accept()

        if not os.fork():
            # close listen fd in child process
            # not actual close, just minus its reference count
            # by one
            listenfd.close()
            tools.str_echo(connfd)
            connfd.close()
            sys.exit(0)

        connfd.close()
开发者ID:woojee001,项目名称:unp-code-in-python,代码行数:33,代码来源:tcpserv02.py


示例20: __init__

    def __init__(self, bot_id):
        self.__log_buffer = []
        self.parameters = Parameters()

        self.__error_retries_counter = 0
        self.__source_pipeline = None
        self.__destination_pipeline = None
        self.logger = None

        try:
            version_info = sys.version.splitlines()[0].strip()
            self.__log_buffer.append(('info',
                                      '{} initialized with id {} and version '
                                      '{} as process {}.'
                                      ''.format(self.__class__.__name__,
                                                bot_id, version_info,
                                                os.getpid())))
            self.__log_buffer.append(('debug', 'Library path: %r.' % __file__))

            self.__load_defaults_configuration()
            self.__load_system_configuration()

            self.__check_bot_id(bot_id)
            self.__bot_id = bot_id

            if self.parameters.logging_handler == 'syslog':
                syslog = self.parameters.logging_syslog
            else:
                syslog = False
            self.logger = utils.log(self.__bot_id, syslog=syslog,
                                    log_path=self.parameters.logging_path,
                                    log_level=self.parameters.logging_level)
        except:
            self.__log_buffer.append(('critical', traceback.format_exc()))
            self.stop()
        else:
            for line in self.__log_buffer:
                getattr(self.logger, line[0])(line[1])

        try:
            self.logger.info('Bot is starting.')
            self.__load_runtime_configuration()
            self.__load_pipeline_configuration()
            self.__load_harmonization_configuration()

            self.init()

            self.__sighup = False
            signal.signal(signal.SIGHUP, self.__handle_sighup_signal)
            # system calls should not be interrupted, but restarted
            signal.siginterrupt(signal.SIGHUP, False)
        except Exception as exc:
            if self.parameters.error_log_exception:
                self.logger.exception('Bot initialization failed.')
            else:
                self.logger.error(utils.error_message_from_exc(exc))
                self.logger.error('Bot initialization failed.')

            self.stop()
            raise
开发者ID:TW-NCERT,项目名称:intelmq,代码行数:60,代码来源:bot.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python signal.signal函数代码示例发布时间:2022-05-27
下一篇:
Python signal.setitimer函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap