本文整理汇总了Python中signal.set_wakeup_fd函数的典型用法代码示例。如果您正苦于以下问题:Python set_wakeup_fd函数的具体用法?Python set_wakeup_fd怎么用?Python set_wakeup_fd使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了set_wakeup_fd函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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
示例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)
示例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)
示例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)
示例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
示例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
示例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
示例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
示例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
示例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)
示例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])
示例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()
示例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)
示例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)