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

Python signal.set_wakeup_fd函数代码示例

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

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



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

示例1: _shutdown_resources

    def _shutdown_resources(self):
        log.debug("Kernel %r shutting down", self)
        if self._notify_sock:
            self._notify_sock.close()
            self._notify_sock = None
            self._wait_sock.close()
            self._wait_sock = None

        if self._signal_sets:
            signal.set_wakeup_fd(-1)
            self._signal_sets = None
            self._default_signals = None

        if self._selector:
            self._selector.close()
            self._selector = None

        if self._thread_pool:
            self._thread_pool.shutdown()
            self._thread_pool = None

        if self._process_pool:
            self._process_pool.shutdown()
            self._process_pool = None

        if self._monitor:
            self._monitor.close()
开发者ID:hiway,项目名称:curio,代码行数:27,代码来源:kernel.py


示例2: remove_signal_handler

    def remove_signal_handler(self, sig):
        """Remove a handler for a signal.  UNIX only.

        Return True if a signal handler was removed, False if not.
        """
        self._check_signal(sig)
        try:
            del self._signal_handlers[sig]
        except KeyError:
            return False

        if sig == signal.SIGINT:
            handler = signal.default_int_handler
        else:
            handler = signal.SIG_DFL

        try:
            signal.signal(sig, handler)
        except OSError as exc:
            if exc.errno == errno.EINVAL:
                raise RuntimeError('sig {} cannot be caught'.format(sig))
            else:
                raise

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

        return True
开发者ID:LPRD,项目名称:build_tools,代码行数:31,代码来源:unix_events.py


示例3: 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


示例4: _setup_signals

    def _setup_signals(self):
        """Set up signal handlers.

        On Windows this uses a QTimer to periodically hand control over to
        Python so it can handle signals.

        On Unix, it uses a QSocketNotifier with os.set_wakeup_fd to get
        notified.
        """
        signal.signal(signal.SIGINT, self.interrupt)
        signal.signal(signal.SIGTERM, self.interrupt)

        if os.name == 'posix' and hasattr(signal, 'set_wakeup_fd'):
            import fcntl
            read_fd, write_fd = os.pipe()
            for fd in (read_fd, write_fd):
                flags = fcntl.fcntl(fd, fcntl.F_GETFL)
                fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
            self._signal_notifier = QSocketNotifier(
                read_fd, QSocketNotifier.Read, self)
            self._signal_notifier.activated.connect(self._handle_signal_wakeup)
            signal.set_wakeup_fd(write_fd)
        else:
            self._signal_timer = usertypes.Timer(self, 'python_hacks')
            self._signal_timer.start(1000)
            self._signal_timer.timeout.connect(lambda: None)
开发者ID:JIVS,项目名称:qutebrowser,代码行数:26,代码来源:app.py


示例5: 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


示例6: _shutdown

        def _shutdown():
            nonlocal njobs
            for task in sorted(tasks.values(), key=lambda t: t.id, reverse=True):
                if task.id == self._kernel_task_id:
                    continue

                # If the task is daemonic, force it to non-daemon status and cancel it
                if task.daemon:
                    njobs += 1
                    task.daemon = False

                assert _cancel_task(task)

            # Run all of the daemon tasks through cancellation
            if ready:
                self.run()

            # Cancel the kernel loopback task (if any)
            task = tasks.pop(self._kernel_task_id, None)
            if task:
                task.cancel_func()
                self._notify_sock.close()
                self._notify_sock = None
                self._wait_sock.close()
                self._wait_sock = None
                self._kernel_task_id = None

            # Remove the signal handling file descriptor (if any)
            if self._signal_sets:
                signal.set_wakeup_fd(-1)
                self._signal_sets = None
                self._default_signals = None
开发者ID:h2non,项目名称:curio,代码行数:32,代码来源:kernel.py


示例7: 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


示例8: register

def register():
    '''
    This function creates a select.poll object that can be used in the same
    manner as signal.pause(). The poll object returns each time a signal was
    received by the process.

    This function has to be called from the main thread.
    '''

    global _signal_poller
    global _signal_read_fd

    if _signal_poller is not None:
        raise RuntimeError('register was already called')

    read_fd, write_fd = os.pipe()

    # Python c-level signal handler requires that the write end will be in
    # non blocking mode
    filecontrol.set_non_blocking(write_fd)

    # Set the read pipe end to non-blocking too, just in case.
    filecontrol.set_non_blocking(read_fd)

    # Prevent subproccesses we execute from inheriting the pipes.
    filecontrol.set_close_on_exec(write_fd)
    filecontrol.set_close_on_exec(read_fd)

    signal.set_wakeup_fd(write_fd)

    poller = select.poll()
    poller.register(read_fd, select.POLLIN)

    _signal_poller = poller
    _signal_read_fd = read_fd
开发者ID:nirs,项目名称:vdsm,代码行数:35,代码来源:sigutils.py


示例9: _handleSignals

 def _handleSignals(self):
     # Bypass installing the child waker, for now
     _SignalReactorMixin._handleSignals(self)
     try:
         signal.set_wakeup_fd(self._signal_fds.writer_fileno())
     except ValueError:
         pass
开发者ID:cyisfor,项目名称:twisted-pyuv,代码行数:7,代码来源:__init__.py


示例10: _signal_pipe

 def _signal_pipe(self):
     # Set up a pipe for SIGCHLD notifications
     wakeup_r, wakeup_w = os.pipe()
     fcntl.fcntl(wakeup_w, fcntl.F_SETFL, # Make the pipe non-blocking
         fcntl.fcntl(wakeup_w, fcntl.F_GETFL, 0) | os.O_NONBLOCK)
     signal.set_wakeup_fd(wakeup_w) # Tell Python to send a byte to this pipe on signal
     signal.signal(signal.SIGCHLD, lambda x,y: None) # Stop ignoring SIGCHLD
     return wakeup_r, wakeup_w
开发者ID:robinhouston,项目名称:process-runner,代码行数:8,代码来源:runner.py


示例11: test_invalid_call

    def test_invalid_call(self):
        # First parameter is positional-only
        with self.assertRaises(TypeError):
            signal.set_wakeup_fd(signum=signal.SIGINT)

        # warn_on_full_buffer is a keyword-only parameter
        with self.assertRaises(TypeError):
            signal.set_wakeup_fd(signal.SIGINT, False)
开发者ID:Eyepea,项目名称:cpython,代码行数:8,代码来源:test_signal.py


示例12: init

    def init(cls):
        """
        Creates a pipe for waking up a select call when a signal has been received.
        """
        cls.__wake_up_pipe = os.pipe()
        fcntl.fcntl(cls.__wake_up_pipe[0], fcntl.F_SETFL, os.O_NONBLOCK)

        signal.set_wakeup_fd(EventQueueEmptyEventHandler.__wake_up_pipe[1])
开发者ID:OlegKlimenko,项目名称:py-enarksh,代码行数:8,代码来源:EventQueueEmptyEventHandler.py


示例13: __init__

    def __init__(self):
        self.lock = threading.RLock()
        self.condition = threading.Condition(self.lock)
        # this lock and conditions are used for:
        #
        # - mutual exclusion and synchronization beetween sections of
        # code in _Conductor.__io_loop (conductor thread), and in
        # Process.start() and Process.wait() (main thread)
        #
        # - mutual exclusion beetween sections of code in
        #   _Conductor.__io_loop() (conductor thread) and in
        #   _Conductor.__reaper_thread_func() (reaper thread)

        self.__io_thread = threading.Thread(target = self.__io_thread_func, name = "I/O")
        self.__io_thread.setDaemon(True)
        # thread will terminate automatically when the main thread
        # exits.  once in a while, this can trigger an exception, but
        # this seems to be safe and to be related to this issue:
        # http://bugs.python.org/issue1856
        self.__rpipe, self.__wpipe = os.pipe()  # pipe used to wakeup
                                                # the conductor thread
                                                # from the main thread
                                                # when needed
        _set_fd_nonblocking(self.__rpipe)   # the reading function
                                            # _read_asmuch() relies on
                                            # file descriptors to be non
                                            # blocking
        _set_fd_nonblocking(self.__wpipe)   # because we call
                                            # signal.set_wakeup_fd on this pipe
        self.__poller = poll()   # asynchronous I/O with all
                                 # subprocesses filehandles
        self.__poller.register(self.__rpipe,
                               POLLIN
                               | POLLERR)
        self.__processes = set()    # the set of `Process` handled by
                                    # this `_Conductor`
        self.__fds = dict() # keys: the file descriptors currently polled by
                            # this `_Conductor`
                            #
                            # values: tuples (`Process`, `Process`'s
                            # function to handle activity for this
                            # descriptor)
        self.__pids = dict()    # keys: the pids of the subprocesses
                                # launched by this `_Conductor`
                                #
                                # values: their `Process`
        self.__timeline = [] # heapq of `Process` with a timeout date
        self.__process_actions = queue.Queue()
                                # thread-safe FIFO used to send requests
                                # from main thread and conductor thread:
                                # we enqueue tuples (function to call,
                                # tuple of parameters to pass to this
                                # function))
        self.__reaper_thread_running = False
                                # to keep track wether reaper thread is
                                # running
        signal.set_wakeup_fd(self.__wpipe)
        self.pgrp = self.__start_pgrp()
开发者ID:mickours,项目名称:execo,代码行数:58,代码来源:conductor.py


示例14: __init__

    def __init__(self):
        self.readmap = {}
        self.writemap = {}

        # Setup the wakeup file descriptor to avoid hanging on lost signals.
        wakeup_readfd, wakeup_writefd = os.pipe()
        fcntl.fcntl(wakeup_writefd, fcntl.F_SETFL, os.O_NONBLOCK)
        self.register_read(wakeup_readfd, self.wakeup_handler)
        signal.set_wakeup_fd(wakeup_writefd)
开发者ID:lilydjwg,项目名称:pssh,代码行数:9,代码来源:manager.py


示例15: dispose

 def dispose(self, exc=None):
     if self.current[0] == self:
         signal.signal(signal.SIGCHLD, signal.SIG_DFL)
         signal.set_wakeup_fd(-1)
         self.current[0] = None
     error = Result.from_exception(exc or CanceledError('process queue has been disposed'))
     pids, self.pids = self.pids, {}
     for ret in self.pids.values():
         ret(error)
开发者ID:aslpavel,项目名称:pretzel,代码行数:9,代码来源:core.py


示例16: __init__

 def __init__(self, zkservers, config_path):
   self._signal_notifier = os.pipe()
   signal.set_wakeup_fd(self._signal_notifier[1])
   signal.signal(signal.SIGCHLD, self._sigchld)
   zh = zkwrapper.ZKWrapper(zkservers)
   core.set_default_zkwrapper(zh)
   core.set_default_ping_fd(self._signal_notifier[1])
   self._inotify_watcher = InotifyWatcher([config_path], ConfigFile,
                                          self._is_config_file)
   self._sigchld_received = False
开发者ID:bdacode,项目名称:twitcher,代码行数:10,代码来源:twitcher.py


示例17: start

    def start(self):
        if self._running:
            raise RuntimeError('IOLoop is already running')
        if not logging.getLogger().handlers:
            # The IOLoop catches and logs exceptions, so it's
            # important that log output be visible.  However, python's
            # default behavior for non-root loggers (prior to python
            # 3.2) is to print an unhelpful "no handlers could be
            # found" message rather than the actual log entry, so we
            # must explicitly configure logging if we've made it this
            # far without anything.
            logging.basicConfig()
        if self._stopped:
            self._stopped = False
            return
        old_current = getattr(IOLoop._current, "instance", None)
        IOLoop._current.instance = self
        self._thread_ident = thread.get_ident()

        # pyuv won't interate the loop if the poll is interrupted by
        # a signal, so make sure we can wake it up to catch signals
        # registered with the signal module
        #
        # If someone has already set a wakeup fd, we don't want to
        # disturb it.  This is an issue for twisted, which does its
        # SIGCHILD processing in response to its own wakeup fd being
        # written to.  As long as the wakeup fd is registered on the IOLoop,
        # the loop will still wake up and everything should work.
        old_wakeup_fd = None
        self._signal_checker.stop()
        if hasattr(signal, 'set_wakeup_fd') and os.name == 'posix':
            # requires python 2.6+, unix.  set_wakeup_fd exists but crashes
            # the python process on windows.
            try:
                old_wakeup_fd = signal.set_wakeup_fd(self._fdwaker.writer.fileno())
                if old_wakeup_fd != -1:
                    # Already set, restore previous value.  This is a little racy,
                    # but there's no clean get_wakeup_fd and in real use the
                    # IOLoop is just started once at the beginning.
                    signal.set_wakeup_fd(old_wakeup_fd)
                    old_wakeup_fd = None
                else:
                    self._signal_checker.start()
            except ValueError:  # non-main thread
                pass

        self._running = True
        self._loop.run(pyuv.UV_RUN_DEFAULT)

        # reset the stopped flag so another start/stop pair can be issued
        self._running = False
        self._stopped = False
        IOLoop._current.instance = old_current
        if old_wakeup_fd is not None:
            signal.set_wakeup_fd(old_wakeup_fd)
开发者ID:alex8224,项目名称:tornaduv,代码行数:55,代码来源:__init__.py


示例18: _set_signal_handlers

    def _set_signal_handlers(self):
        """Set the signal handlers."""
        def noopSignalHandler(*args):
            pass
        self._sigchld_handler = signal.signal(signal.SIGCHLD, noopSignalHandler)
        self._sigint_handler  = signal.signal(signal.SIGINT,  noopSignalHandler)
        self._sigterm_handler = signal.signal(signal.SIGTERM, noopSignalHandler)

        sig_r_fd, sig_w_fd = os.pipe2(os.O_NONBLOCK | os.O_CLOEXEC)
        signal.set_wakeup_fd(sig_w_fd)
        self._add_read_fd_handler(sig_r_fd, self._handle_sig_fd, None)
开发者ID:ubuntu-libertine,项目名称:libertine,代码行数:11,代码来源:session.py


示例19: add_signal_watch

def add_signal_watch(signal_action, _sockets=[]):
    """Catches signals which should exit the program and calls `signal_action`
    after the main loop has started, even if the signal occurred before the
    main loop has started.
    """

    # See https://bugzilla.gnome.org/show_bug.cgi?id=622084 for details

    sig_names = ["SIGINT", "SIGTERM", "SIGHUP"]
    if os.name == "nt":
        sig_names = ["SIGINT", "SIGTERM"]

    signals = {}
    for name in sig_names:
        id_ = getattr(signal, name, None)
        if id_ is None:
            continue
        signals[id_] = name

    for signum, name in signals.items():
        # Before the mainloop starts we catch signals in python
        # directly and idle_add the app.quit
        def idle_handler(signum, frame):
            print_d("Python signal handler activated: %s" % signals[signum])
            GLib.idle_add(signal_action, priority=GLib.PRIORITY_HIGH)

        print_d("Register Python signal handler: %r" % name)
        signal.signal(signum, idle_handler)

    read_socket, write_socket = socket.socketpair()
    for sock in [read_socket, write_socket]:
        sock.setblocking(False)
        # prevent it from being GCed and leak it
        _sockets.append(sock)

    def signal_notify(source, condition):
        if condition & GLib.IOCondition.IN:
            try:
                return bool(read_socket.recv(1))
            except EnvironmentError:
                return False
        else:
            return False

    if os.name == "nt":
        channel = GLib.IOChannel.win32_new_socket(read_socket.fileno())
    else:
        channel = GLib.IOChannel.unix_new(read_socket.fileno())
    io_add_watch(channel, GLib.PRIORITY_HIGH,
                 (GLib.IOCondition.IN | GLib.IOCondition.HUP |
                  GLib.IOCondition.NVAL | GLib.IOCondition.ERR),
                 signal_notify)

    signal.set_wakeup_fd(write_socket.fileno())
开发者ID:LudoBike,项目名称:quodlibet,代码行数:54,代码来源:__init__.py


示例20: _shutdown_resources

    def _shutdown_resources(self):
        if self._notify_sock:
            self._notify_sock.close()
            self._notify_sock = None
            self._wait_sock.close()
            self._wait_sock = None

        if self._signal_sets:
            signal.set_wakeup_fd(-1)
            self._signal_sets = None
            self._default_signals = None
开发者ID:adamchainz,项目名称:curio,代码行数:11,代码来源:kernel.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python signal.setitimer函数代码示例发布时间:2022-05-27
下一篇:
Python signal.pthread_sigmask函数代码示例发布时间: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