1 # -*- coding: utf-8 -*-
2 # Copyright 2017 Christoph Reiter
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 from __future__
import print_function
25 from contextlib
import closing
, contextmanager
28 def ensure_socket_not_inheritable(sock
):
29 """Ensures that the socket is not inherited by child processes
33 NotImplementedError: With Python <3.4 on Windows
36 if hasattr(sock
, "set_inheritable"):
37 sock
.set_inheritable(False)
42 raise NotImplementedError(
43 "Not implemented for older Python on Windows")
46 flags
= fcntl
.fcntl(fd
, fcntl
.F_GETFD
)
47 fcntl
.fcntl(fd
, fcntl
.F_SETFD
, flags | fcntl
.FD_CLOEXEC
)
50 _wakeup_fd_is_active
= False
51 """Since we can't check if set_wakeup_fd() is already used for nested event
52 loops without introducing a race condition we keep track of it globally.
57 def wakeup_on_signal():
58 """A decorator for functions which create a glib event loop to keep
59 Python signal handlers working while the event loop is idling.
61 In case an OS signal is received will wake the default event loop up
62 shortly so that any registered Python signal handlers registered through
63 signal.signal() can run.
65 Works on Windows but needs Python 3.5+.
67 In case the wrapped function is not called from the main thread it will be
68 called as is and it will not wake up the default loop for signals.
71 global _wakeup_fd_is_active
73 if _wakeup_fd_is_active
:
77 from gi
.repository
import GLib
79 # On Windows only Python 3.5+ supports passing sockets to set_wakeup_fd
80 set_wakeup_fd_supports_socket
= (
81 os
.name
!= "nt" or sys
.version_info
[:2] >= (3, 5))
82 # On Windows only Python 3 has an implementation of socketpair()
83 has_socketpair
= hasattr(socket
, "socketpair")
85 if not has_socketpair
or not set_wakeup_fd_supports_socket
:
89 read_socket
, write_socket
= socket
.socketpair()
90 with
closing(read_socket
), closing(write_socket
):
92 for sock
in [read_socket
, write_socket
]:
93 sock
.setblocking(False)
94 ensure_socket_not_inheritable(sock
)
97 orig_fd
= signal
.set_wakeup_fd(write_socket
.fileno())
99 # Raised in case this is not the main thread -> give up.
103 _wakeup_fd_is_active
= True
105 def signal_notify(source
, condition
):
106 if condition
& GLib
.IO_IN
:
108 return bool(read_socket
.recv(1))
109 except EnvironmentError as e
:
118 channel
= GLib
.IOChannel
.win32_new_socket(
119 read_socket
.fileno())
121 channel
= GLib
.IOChannel
.unix_new(read_socket
.fileno())
123 source_id
= GLib
.io_add_watch(
125 GLib
.PRIORITY_DEFAULT
,
126 (GLib
.IOCondition
.IN | GLib
.IOCondition
.HUP |
127 GLib
.IOCondition
.NVAL | GLib
.IOCondition
.ERR
),
132 GLib
.source_remove(source_id
)
134 write_fd
= signal
.set_wakeup_fd(orig_fd
)
135 if write_fd
!= write_socket
.fileno():
136 # Someone has called set_wakeup_fd while func() was active,
137 # so let's re-revert again.
138 signal
.set_wakeup_fd(write_fd
)
139 _wakeup_fd_is_active
= False
142 def create_pythonapi():
143 # We need our own instance of ctypes.pythonapi so we don't modify the
144 # global shared one. Adapted from the ctypes source.
146 return ctypes
.PyDLL("python dll", None, sys
.dllhandle
)
147 elif sys
.platform
== "cygwin":
148 return ctypes
.PyDLL("libpython%d.%d.dll" % sys
.version_info
[:2])
150 return ctypes
.PyDLL(None)
153 pydll
= create_pythonapi()
154 PyOS_getsig
= pydll
.PyOS_getsig
155 PyOS_getsig
.restype
= ctypes
.c_void_p
156 PyOS_getsig
.argtypes
= [ctypes
.c_int
]
158 # We save the signal pointer so we can detect if glib has changed the
159 # signal handler behind Python's back (GLib.unix_signal_add)
160 if signal
.getsignal(signal
.SIGINT
) is signal
.default_int_handler
:
161 startup_sigint_ptr
= PyOS_getsig(signal
.SIGINT
)
163 # Something has set the handler before import, we can't get a ptr
164 # for the default handler so make sure the pointer will never match.
165 startup_sigint_ptr
= -1
168 def sigint_handler_is_default():
169 """Returns if on SIGINT the default Python handler would be called"""
171 return (signal
.getsignal(signal
.SIGINT
) is signal
.default_int_handler
and
172 PyOS_getsig(signal
.SIGINT
) == startup_sigint_ptr
)
176 def sigint_handler_set_and_restore_default(handler
):
177 """Context manager for saving/restoring the SIGINT handler default state.
179 Will only restore the default handler again if the handler is not changed
180 while the context is active.
183 assert sigint_handler_is_default()
185 signal
.signal(signal
.SIGINT
, handler
)
186 sig_ptr
= PyOS_getsig(signal
.SIGINT
)
190 if signal
.getsignal(signal
.SIGINT
) is handler
and \
191 PyOS_getsig(signal
.SIGINT
) == sig_ptr
:
192 signal
.signal(signal
.SIGINT
, signal
.default_int_handler
)
195 def is_main_thread():
196 """Returns True in case the function is called from the main thread"""
198 return threading
.current_thread().name
== "MainThread"
202 _sigint_called
= False
206 def register_sigint_fallback(callback
):
207 """Installs a SIGINT signal handler in case the default Python one is
208 active which calls 'callback' in case the signal occurs.
210 Only does something if called from the main thread.
212 In case of nested context managers the signal handler will be only
213 installed once and the callbacks will be called in the reverse order
214 of their registration.
216 The old signal handler will be restored in case no signal handler is
217 registered while the context is active.
220 # To handle multiple levels of event loops we need to call the last
221 # callback first, wait until the inner most event loop returns control
222 # and only then call the next callback, and so on... until we
223 # reach the outer most which manages the signal handler and raises
226 global _callback_stack
, _sigint_called
228 if not is_main_thread():
232 if not sigint_handler_is_default():
234 # This is an inner event loop, append our callback
235 # to the stack so the parent context can call it.
236 _callback_stack
.append(callback
)
241 _callback_stack
.pop()()
243 # There is a signal handler set by the user, just do nothing
247 _sigint_called
= False
249 def sigint_handler(sig_num
, frame
):
250 global _callback_stack
, _sigint_called
254 _sigint_called
= True
255 _callback_stack
.pop()()
257 _callback_stack
.append(callback
)
258 with
sigint_handler_set_and_restore_default(sigint_handler
):
263 signal
.default_int_handler()