blob: d183f60722cffe7aa224f2819e7861aca33d3990 [file] [log] [blame]
Yury Selivanovdec1a452014-02-18 22:27:48 -05001"""Selector event loop for Unix with signal handling."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07002
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07003import errno
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07004import os
5import signal
6import socket
7import stat
8import subprocess
9import sys
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -080010import threading
Victor Stinner978a9af2015-01-29 17:50:58 +010011import warnings
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070012
13
Yury Selivanovb057c522014-02-18 12:15:06 -050014from . import base_events
Guido van Rossum59691282013-10-30 14:52:03 -070015from . import base_subprocess
Yury Selivanov2a8911c2015-08-04 15:56:33 -040016from . import compat
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070017from . import constants
Guido van Rossume36fcde2014-11-14 11:45:47 -080018from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070019from . import events
Victor Stinner47cd10d2015-01-30 00:05:19 +010020from . import futures
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070021from . import selector_events
Victor Stinnere912e652014-07-12 03:11:53 +020022from . import selectors
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070023from . import transports
Victor Stinnerf951d282014-06-29 00:46:45 +020024from .coroutines import coroutine
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070025from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070026
27
Victor Stinner915bcb02014-02-01 22:49:59 +010028__all__ = ['SelectorEventLoop',
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -080029 'AbstractChildWatcher', 'SafeChildWatcher',
30 'FastChildWatcher', 'DefaultEventLoopPolicy',
31 ]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070032
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070033if sys.platform == 'win32': # pragma: no cover
34 raise ImportError('Signals are not really supported on Windows')
35
36
Victor Stinnerfe5649c2014-07-17 22:43:40 +020037def _sighandler_noop(signum, frame):
38 """Dummy signal handler."""
39 pass
40
41
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -080042class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
Yury Selivanovb057c522014-02-18 12:15:06 -050043 """Unix event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070044
Yury Selivanovb057c522014-02-18 12:15:06 -050045 Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070046 """
47
48 def __init__(self, selector=None):
49 super().__init__(selector)
50 self._signal_handlers = {}
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070051
52 def _socketpair(self):
53 return socket.socketpair()
54
Guido van Rossum0b69fbc2013-11-06 20:25:50 -080055 def close(self):
Victor Stinnerf328c7d2014-06-23 01:02:37 +020056 super().close()
Guido van Rossum0b69fbc2013-11-06 20:25:50 -080057 for sig in list(self._signal_handlers):
58 self.remove_signal_handler(sig)
Guido van Rossum0b69fbc2013-11-06 20:25:50 -080059
Victor Stinnerfe5649c2014-07-17 22:43:40 +020060 def _process_self_data(self, data):
61 for signum in data:
62 if not signum:
63 # ignore null bytes written by _write_to_self()
64 continue
65 self._handle_signal(signum)
66
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070067 def add_signal_handler(self, sig, callback, *args):
68 """Add a handler for a signal. UNIX only.
69
70 Raise ValueError if the signal number is invalid or uncatchable.
71 Raise RuntimeError if there is a problem setting up the handler.
72 """
Victor Stinner2d99d932014-11-20 15:03:52 +010073 if (coroutines.iscoroutine(callback)
74 or coroutines.iscoroutinefunction(callback)):
Victor Stinner15cc6782015-01-09 00:09:10 +010075 raise TypeError("coroutines cannot be used "
76 "with add_signal_handler()")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070077 self._check_signal(sig)
Victor Stinnere80bf0d2014-12-04 23:07:47 +010078 self._check_closed()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070079 try:
80 # set_wakeup_fd() raises ValueError if this is not the
81 # main thread. By calling it early we ensure that an
82 # event loop running in another thread cannot add a signal
83 # handler.
84 signal.set_wakeup_fd(self._csock.fileno())
Victor Stinnerc4c46492014-07-23 18:21:45 +020085 except (ValueError, OSError) as exc:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070086 raise RuntimeError(str(exc))
87
Yury Selivanov569efa22014-02-18 18:02:19 -050088 handle = events.Handle(callback, args, self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070089 self._signal_handlers[sig] = handle
90
91 try:
Victor Stinnerfe5649c2014-07-17 22:43:40 +020092 # Register a dummy signal handler to ask Python to write the signal
93 # number in the wakup file descriptor. _process_self_data() will
94 # read signal numbers from this file descriptor to handle signals.
95 signal.signal(sig, _sighandler_noop)
96
Charles-François Natali74e7cf32013-12-05 22:47:19 +010097 # Set SA_RESTART to limit EINTR occurrences.
98 signal.siginterrupt(sig, False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070099 except OSError as exc:
100 del self._signal_handlers[sig]
101 if not self._signal_handlers:
102 try:
103 signal.set_wakeup_fd(-1)
Victor Stinnerc4c46492014-07-23 18:21:45 +0200104 except (ValueError, OSError) as nexc:
Guido van Rossumfc29e0f2013-10-17 15:39:45 -0700105 logger.info('set_wakeup_fd(-1) failed: %s', nexc)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700106
107 if exc.errno == errno.EINVAL:
108 raise RuntimeError('sig {} cannot be caught'.format(sig))
109 else:
110 raise
111
Victor Stinnerfe5649c2014-07-17 22:43:40 +0200112 def _handle_signal(self, sig):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700113 """Internal helper that is the actual signal handler."""
114 handle = self._signal_handlers.get(sig)
115 if handle is None:
116 return # Assume it's some race condition.
117 if handle._cancelled:
118 self.remove_signal_handler(sig) # Remove it properly.
119 else:
120 self._add_callback_signalsafe(handle)
121
122 def remove_signal_handler(self, sig):
123 """Remove a handler for a signal. UNIX only.
124
125 Return True if a signal handler was removed, False if not.
126 """
127 self._check_signal(sig)
128 try:
129 del self._signal_handlers[sig]
130 except KeyError:
131 return False
132
133 if sig == signal.SIGINT:
134 handler = signal.default_int_handler
135 else:
136 handler = signal.SIG_DFL
137
138 try:
139 signal.signal(sig, handler)
140 except OSError as exc:
141 if exc.errno == errno.EINVAL:
142 raise RuntimeError('sig {} cannot be caught'.format(sig))
143 else:
144 raise
145
146 if not self._signal_handlers:
147 try:
148 signal.set_wakeup_fd(-1)
Victor Stinnerc4c46492014-07-23 18:21:45 +0200149 except (ValueError, OSError) as exc:
Guido van Rossumfc29e0f2013-10-17 15:39:45 -0700150 logger.info('set_wakeup_fd(-1) failed: %s', exc)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700151
152 return True
153
154 def _check_signal(self, sig):
155 """Internal helper to validate a signal.
156
157 Raise ValueError if the signal number is invalid or uncatchable.
158 Raise RuntimeError if there is a problem setting up the handler.
159 """
160 if not isinstance(sig, int):
161 raise TypeError('sig must be an int, not {!r}'.format(sig))
162
163 if not (1 <= sig < signal.NSIG):
164 raise ValueError(
165 'sig {} out of range(1, {})'.format(sig, signal.NSIG))
166
167 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
168 extra=None):
169 return _UnixReadPipeTransport(self, pipe, protocol, waiter, extra)
170
171 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
172 extra=None):
173 return _UnixWritePipeTransport(self, pipe, protocol, waiter, extra)
174
Victor Stinnerf951d282014-06-29 00:46:45 +0200175 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700176 def _make_subprocess_transport(self, protocol, args, shell,
177 stdin, stdout, stderr, bufsize,
178 extra=None, **kwargs):
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800179 with events.get_child_watcher() as watcher:
Yury Selivanov7661db62016-05-16 15:38:39 -0400180 waiter = self.create_future()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800181 transp = _UnixSubprocessTransport(self, protocol, args, shell,
182 stdin, stdout, stderr, bufsize,
Victor Stinner47cd10d2015-01-30 00:05:19 +0100183 waiter=waiter, extra=extra,
184 **kwargs)
185
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800186 watcher.add_child_handler(transp.get_pid(),
187 self._child_watcher_callback, transp)
Victor Stinner47cd10d2015-01-30 00:05:19 +0100188 try:
189 yield from waiter
Victor Stinner5d44c082015-02-02 18:36:31 +0100190 except Exception as exc:
191 # Workaround CPython bug #23353: using yield/yield-from in an
192 # except block of a generator doesn't clear properly
193 # sys.exc_info()
194 err = exc
195 else:
196 err = None
197
198 if err is not None:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100199 transp.close()
Victor Stinner1241ecc2015-01-30 00:16:14 +0100200 yield from transp._wait()
Victor Stinner5d44c082015-02-02 18:36:31 +0100201 raise err
Guido van Rossum4835f172014-01-10 13:28:59 -0800202
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700203 return transp
204
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800205 def _child_watcher_callback(self, pid, returncode, transp):
206 self.call_soon_threadsafe(transp._process_exited, returncode)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700207
Victor Stinnerf951d282014-06-29 00:46:45 +0200208 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500209 def create_unix_connection(self, protocol_factory, path, *,
210 ssl=None, sock=None,
211 server_hostname=None):
212 assert server_hostname is None or isinstance(server_hostname, str)
213 if ssl:
214 if server_hostname is None:
215 raise ValueError(
216 'you have to pass server_hostname when using ssl')
217 else:
218 if server_hostname is not None:
219 raise ValueError('server_hostname is only meaningful with ssl')
220
221 if path is not None:
222 if sock is not None:
223 raise ValueError(
224 'path and sock can not be specified at the same time')
225
Victor Stinner79a29522014-02-19 01:45:59 +0100226 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
Yury Selivanovb057c522014-02-18 12:15:06 -0500227 try:
Yury Selivanovb057c522014-02-18 12:15:06 -0500228 sock.setblocking(False)
229 yield from self.sock_connect(sock, path)
Victor Stinner79a29522014-02-19 01:45:59 +0100230 except:
231 sock.close()
Yury Selivanovb057c522014-02-18 12:15:06 -0500232 raise
233
234 else:
235 if sock is None:
236 raise ValueError('no path and sock were specified')
237 sock.setblocking(False)
238
239 transport, protocol = yield from self._create_connection_transport(
240 sock, protocol_factory, ssl, server_hostname)
241 return transport, protocol
242
Victor Stinnerf951d282014-06-29 00:46:45 +0200243 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500244 def create_unix_server(self, protocol_factory, path=None, *,
245 sock=None, backlog=100, ssl=None):
246 if isinstance(ssl, bool):
247 raise TypeError('ssl argument must be an SSLContext or None')
248
249 if path is not None:
Victor Stinner1fd03a42014-04-07 11:18:54 +0200250 if sock is not None:
251 raise ValueError(
252 'path and sock can not be specified at the same time')
253
Yury Selivanovb057c522014-02-18 12:15:06 -0500254 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
255
256 try:
257 sock.bind(path)
258 except OSError as exc:
Victor Stinner79a29522014-02-19 01:45:59 +0100259 sock.close()
Yury Selivanovb057c522014-02-18 12:15:06 -0500260 if exc.errno == errno.EADDRINUSE:
261 # Let's improve the error message by adding
262 # with what exact address it occurs.
263 msg = 'Address {!r} is already in use'.format(path)
264 raise OSError(errno.EADDRINUSE, msg) from None
265 else:
266 raise
Victor Stinner223a6242014-06-04 00:11:52 +0200267 except:
268 sock.close()
269 raise
Yury Selivanovb057c522014-02-18 12:15:06 -0500270 else:
271 if sock is None:
272 raise ValueError(
273 'path was not specified, and no sock specified')
274
275 if sock.family != socket.AF_UNIX:
276 raise ValueError(
277 'A UNIX Domain Socket was expected, got {!r}'.format(sock))
278
279 server = base_events.Server(self, [sock])
280 sock.listen(backlog)
281 sock.setblocking(False)
282 self._start_serving(protocol_factory, sock, ssl, server)
283 return server
284
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700285
Victor Stinnerf2ed8892014-07-29 23:08:00 +0200286if hasattr(os, 'set_blocking'):
287 def _set_nonblocking(fd):
288 os.set_blocking(fd, False)
289else:
Yury Selivanov8c0e0ab2014-09-24 23:21:39 -0400290 import fcntl
291
Victor Stinnerf2ed8892014-07-29 23:08:00 +0200292 def _set_nonblocking(fd):
293 flags = fcntl.fcntl(fd, fcntl.F_GETFL)
294 flags = flags | os.O_NONBLOCK
295 fcntl.fcntl(fd, fcntl.F_SETFL, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700296
297
298class _UnixReadPipeTransport(transports.ReadTransport):
299
Yury Selivanovdec1a452014-02-18 22:27:48 -0500300 max_size = 256 * 1024 # max bytes we read in one event loop iteration
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700301
302 def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
303 super().__init__(extra)
304 self._extra['pipe'] = pipe
305 self._loop = loop
306 self._pipe = pipe
307 self._fileno = pipe.fileno()
Guido van Rossum47867872016-08-31 09:42:38 -0700308 self._protocol = protocol
309 self._closing = False
310
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700311 mode = os.fstat(self._fileno).st_mode
Guido van Rossum02757ea2014-01-10 13:30:04 -0800312 if not (stat.S_ISFIFO(mode) or
313 stat.S_ISSOCK(mode) or
314 stat.S_ISCHR(mode)):
Guido van Rossum47867872016-08-31 09:42:38 -0700315 self._pipe = None
316 self._fileno = None
317 self._protocol = None
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700318 raise ValueError("Pipe transport is for pipes/sockets only.")
Guido van Rossum47867872016-08-31 09:42:38 -0700319
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700320 _set_nonblocking(self._fileno)
Guido van Rossum47867872016-08-31 09:42:38 -0700321
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700322 self._loop.call_soon(self._protocol.connection_made, self)
Victor Stinner29342622015-01-29 14:15:19 +0100323 # only start reading when connection_made() has been called
324 self._loop.call_soon(self._loop.add_reader,
325 self._fileno, self._read_ready)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700326 if waiter is not None:
Victor Stinnerf07801b2015-01-29 00:36:35 +0100327 # only wake up the waiter when connection_made() has been called
Yury Selivanov5d7e3b62015-11-17 12:19:41 -0500328 self._loop.call_soon(futures._set_result_unless_cancelled,
329 waiter, None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700330
Victor Stinnere912e652014-07-12 03:11:53 +0200331 def __repr__(self):
Victor Stinner29ad0112015-01-15 00:04:21 +0100332 info = [self.__class__.__name__]
333 if self._pipe is None:
334 info.append('closed')
335 elif self._closing:
336 info.append('closing')
337 info.append('fd=%s' % self._fileno)
Yury Selivanov5dc09332016-05-13 16:04:43 -0400338 selector = getattr(self._loop, '_selector', None)
339 if self._pipe is not None and selector is not None:
Victor Stinnere912e652014-07-12 03:11:53 +0200340 polling = selector_events._test_selector_event(
Yury Selivanov5dc09332016-05-13 16:04:43 -0400341 selector,
Victor Stinnere912e652014-07-12 03:11:53 +0200342 self._fileno, selectors.EVENT_READ)
343 if polling:
344 info.append('polling')
345 else:
346 info.append('idle')
Yury Selivanov5dc09332016-05-13 16:04:43 -0400347 elif self._pipe is not None:
348 info.append('open')
Victor Stinnere912e652014-07-12 03:11:53 +0200349 else:
350 info.append('closed')
351 return '<%s>' % ' '.join(info)
352
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700353 def _read_ready(self):
354 try:
355 data = os.read(self._fileno, self.max_size)
356 except (BlockingIOError, InterruptedError):
357 pass
358 except OSError as exc:
Victor Stinner0ee29c22014-02-19 01:40:41 +0100359 self._fatal_error(exc, 'Fatal read error on pipe transport')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700360 else:
361 if data:
362 self._protocol.data_received(data)
363 else:
Victor Stinnere912e652014-07-12 03:11:53 +0200364 if self._loop.get_debug():
365 logger.info("%r was closed by peer", self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700366 self._closing = True
367 self._loop.remove_reader(self._fileno)
368 self._loop.call_soon(self._protocol.eof_received)
369 self._loop.call_soon(self._call_connection_lost, None)
370
Guido van Rossum57497ad2013-10-18 07:58:20 -0700371 def pause_reading(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700372 self._loop.remove_reader(self._fileno)
373
Guido van Rossum57497ad2013-10-18 07:58:20 -0700374 def resume_reading(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700375 self._loop.add_reader(self._fileno, self._read_ready)
376
Yury Selivanov5bb1afb2015-11-16 12:43:21 -0500377 def is_closing(self):
378 return self._closing
379
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700380 def close(self):
381 if not self._closing:
382 self._close(None)
383
Victor Stinner978a9af2015-01-29 17:50:58 +0100384 # On Python 3.3 and older, objects with a destructor part of a reference
385 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
386 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400387 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100388 def __del__(self):
389 if self._pipe is not None:
Victor Stinnere19558a2016-03-23 00:28:08 +0100390 warnings.warn("unclosed transport %r" % self, ResourceWarning,
391 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100392 self._pipe.close()
393
Victor Stinner0ee29c22014-02-19 01:40:41 +0100394 def _fatal_error(self, exc, message='Fatal error on pipe transport'):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700395 # should be called by exception handler only
Victor Stinnerb2614752014-08-25 23:20:52 +0200396 if (isinstance(exc, OSError) and exc.errno == errno.EIO):
397 if self._loop.get_debug():
398 logger.debug("%r: %s", self, message, exc_info=True)
399 else:
Yury Selivanov569efa22014-02-18 18:02:19 -0500400 self._loop.call_exception_handler({
Victor Stinner0ee29c22014-02-19 01:40:41 +0100401 'message': message,
Yury Selivanov569efa22014-02-18 18:02:19 -0500402 'exception': exc,
403 'transport': self,
404 'protocol': self._protocol,
405 })
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700406 self._close(exc)
407
408 def _close(self, exc):
409 self._closing = True
410 self._loop.remove_reader(self._fileno)
411 self._loop.call_soon(self._call_connection_lost, exc)
412
413 def _call_connection_lost(self, exc):
414 try:
415 self._protocol.connection_lost(exc)
416 finally:
417 self._pipe.close()
418 self._pipe = None
419 self._protocol = None
420 self._loop = None
421
422
Yury Selivanov3cb99142014-02-18 18:41:13 -0500423class _UnixWritePipeTransport(transports._FlowControlMixin,
Guido van Rossum47fb97e2014-01-29 13:20:39 -0800424 transports.WriteTransport):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700425
426 def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
Victor Stinner004adb92014-11-05 15:27:41 +0100427 super().__init__(extra, loop)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700428 self._extra['pipe'] = pipe
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700429 self._pipe = pipe
430 self._fileno = pipe.fileno()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700431 self._protocol = protocol
432 self._buffer = []
433 self._conn_lost = 0
434 self._closing = False # Set when close() or write_eof() called.
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700435
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700436 mode = os.fstat(self._fileno).st_mode
Guido van Rossum8b7918a2016-08-31 09:40:18 -0700437 is_char = stat.S_ISCHR(mode)
438 is_fifo = stat.S_ISFIFO(mode)
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700439 is_socket = stat.S_ISSOCK(mode)
Guido van Rossum8b7918a2016-08-31 09:40:18 -0700440 if not (is_char or is_fifo or is_socket):
Guido van Rossum47867872016-08-31 09:42:38 -0700441 self._pipe = None
442 self._fileno = None
443 self._protocol = None
Victor Stinner8dffc452014-01-25 15:32:06 +0100444 raise ValueError("Pipe transport is only for "
445 "pipes, sockets and character devices")
Guido van Rossum47867872016-08-31 09:42:38 -0700446
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700447 _set_nonblocking(self._fileno)
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700448
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700449 self._loop.call_soon(self._protocol.connection_made, self)
Victor Stinner29342622015-01-29 14:15:19 +0100450
451 # On AIX, the reader trick (to be notified when the read end of the
452 # socket is closed) only works for sockets. On other platforms it
453 # works for pipes and sockets. (Exception: OS X 10.4? Issue #19294.)
Guido van Rossum8b7918a2016-08-31 09:40:18 -0700454 if is_socket or (is_fifo and not sys.platform.startswith("aix")):
Victor Stinner29342622015-01-29 14:15:19 +0100455 # only start reading when connection_made() has been called
456 self._loop.call_soon(self._loop.add_reader,
457 self._fileno, self._read_ready)
458
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700459 if waiter is not None:
Victor Stinnerf07801b2015-01-29 00:36:35 +0100460 # only wake up the waiter when connection_made() has been called
Yury Selivanov5d7e3b62015-11-17 12:19:41 -0500461 self._loop.call_soon(futures._set_result_unless_cancelled,
462 waiter, None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700463
Victor Stinnere912e652014-07-12 03:11:53 +0200464 def __repr__(self):
Victor Stinner29ad0112015-01-15 00:04:21 +0100465 info = [self.__class__.__name__]
466 if self._pipe is None:
467 info.append('closed')
468 elif self._closing:
469 info.append('closing')
470 info.append('fd=%s' % self._fileno)
Yury Selivanov5dc09332016-05-13 16:04:43 -0400471 selector = getattr(self._loop, '_selector', None)
472 if self._pipe is not None and selector is not None:
Victor Stinnere912e652014-07-12 03:11:53 +0200473 polling = selector_events._test_selector_event(
Yury Selivanov5dc09332016-05-13 16:04:43 -0400474 selector,
Victor Stinnere912e652014-07-12 03:11:53 +0200475 self._fileno, selectors.EVENT_WRITE)
476 if polling:
477 info.append('polling')
478 else:
479 info.append('idle')
480
481 bufsize = self.get_write_buffer_size()
482 info.append('bufsize=%s' % bufsize)
Yury Selivanov5dc09332016-05-13 16:04:43 -0400483 elif self._pipe is not None:
484 info.append('open')
Victor Stinnere912e652014-07-12 03:11:53 +0200485 else:
486 info.append('closed')
487 return '<%s>' % ' '.join(info)
488
Guido van Rossum47fb97e2014-01-29 13:20:39 -0800489 def get_write_buffer_size(self):
490 return sum(len(data) for data in self._buffer)
491
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700492 def _read_ready(self):
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700493 # Pipe was closed by peer.
Victor Stinnere912e652014-07-12 03:11:53 +0200494 if self._loop.get_debug():
495 logger.info("%r was closed by peer", self)
Victor Stinner61b3c9b2014-01-31 13:04:28 +0100496 if self._buffer:
497 self._close(BrokenPipeError())
498 else:
499 self._close()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700500
501 def write(self, data):
Guido van Rossum47fb97e2014-01-29 13:20:39 -0800502 assert isinstance(data, (bytes, bytearray, memoryview)), repr(data)
503 if isinstance(data, bytearray):
504 data = memoryview(data)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700505 if not data:
506 return
507
508 if self._conn_lost or self._closing:
509 if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
Guido van Rossumfc29e0f2013-10-17 15:39:45 -0700510 logger.warning('pipe closed by peer or '
511 'os.write(pipe, data) raised exception.')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700512 self._conn_lost += 1
513 return
514
515 if not self._buffer:
516 # Attempt to send it right away first.
517 try:
518 n = os.write(self._fileno, data)
519 except (BlockingIOError, InterruptedError):
520 n = 0
521 except Exception as exc:
522 self._conn_lost += 1
Victor Stinner0ee29c22014-02-19 01:40:41 +0100523 self._fatal_error(exc, 'Fatal write error on pipe transport')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700524 return
525 if n == len(data):
526 return
527 elif n > 0:
528 data = data[n:]
529 self._loop.add_writer(self._fileno, self._write_ready)
530
531 self._buffer.append(data)
Guido van Rossum47fb97e2014-01-29 13:20:39 -0800532 self._maybe_pause_protocol()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700533
534 def _write_ready(self):
535 data = b''.join(self._buffer)
536 assert data, 'Data should not be empty'
537
538 self._buffer.clear()
539 try:
540 n = os.write(self._fileno, data)
541 except (BlockingIOError, InterruptedError):
542 self._buffer.append(data)
543 except Exception as exc:
544 self._conn_lost += 1
545 # Remove writer here, _fatal_error() doesn't it
546 # because _buffer is empty.
547 self._loop.remove_writer(self._fileno)
Victor Stinner0ee29c22014-02-19 01:40:41 +0100548 self._fatal_error(exc, 'Fatal write error on pipe transport')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700549 else:
550 if n == len(data):
551 self._loop.remove_writer(self._fileno)
Guido van Rossum47fb97e2014-01-29 13:20:39 -0800552 self._maybe_resume_protocol() # May append to buffer.
553 if not self._buffer and self._closing:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700554 self._loop.remove_reader(self._fileno)
555 self._call_connection_lost(None)
556 return
557 elif n > 0:
558 data = data[n:]
559
560 self._buffer.append(data) # Try again later.
561
562 def can_write_eof(self):
563 return True
564
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700565 def write_eof(self):
566 if self._closing:
567 return
568 assert self._pipe
569 self._closing = True
570 if not self._buffer:
571 self._loop.remove_reader(self._fileno)
572 self._loop.call_soon(self._call_connection_lost, None)
573
Yury Selivanov5bb1afb2015-11-16 12:43:21 -0500574 def is_closing(self):
575 return self._closing
576
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700577 def close(self):
Victor Stinner41ed9582015-01-15 13:16:50 +0100578 if self._pipe is not None and not self._closing:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700579 # write_eof is all what we needed to close the write pipe
580 self.write_eof()
581
Victor Stinner978a9af2015-01-29 17:50:58 +0100582 # On Python 3.3 and older, objects with a destructor part of a reference
583 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
584 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400585 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100586 def __del__(self):
587 if self._pipe is not None:
Victor Stinnere19558a2016-03-23 00:28:08 +0100588 warnings.warn("unclosed transport %r" % self, ResourceWarning,
589 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100590 self._pipe.close()
591
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700592 def abort(self):
593 self._close(None)
594
Victor Stinner0ee29c22014-02-19 01:40:41 +0100595 def _fatal_error(self, exc, message='Fatal error on pipe transport'):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700596 # should be called by exception handler only
Victor Stinnerc94a93a2016-04-01 21:43:39 +0200597 if isinstance(exc, base_events._FATAL_ERROR_IGNORE):
Victor Stinnerb2614752014-08-25 23:20:52 +0200598 if self._loop.get_debug():
599 logger.debug("%r: %s", self, message, exc_info=True)
600 else:
Yury Selivanov569efa22014-02-18 18:02:19 -0500601 self._loop.call_exception_handler({
Victor Stinner0ee29c22014-02-19 01:40:41 +0100602 'message': message,
Yury Selivanov569efa22014-02-18 18:02:19 -0500603 'exception': exc,
604 'transport': self,
605 'protocol': self._protocol,
606 })
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700607 self._close(exc)
608
609 def _close(self, exc=None):
610 self._closing = True
611 if self._buffer:
612 self._loop.remove_writer(self._fileno)
613 self._buffer.clear()
614 self._loop.remove_reader(self._fileno)
615 self._loop.call_soon(self._call_connection_lost, exc)
616
617 def _call_connection_lost(self, exc):
618 try:
619 self._protocol.connection_lost(exc)
620 finally:
621 self._pipe.close()
622 self._pipe = None
623 self._protocol = None
624 self._loop = None
625
626
Victor Stinner1e40f102014-12-11 23:30:17 +0100627if hasattr(os, 'set_inheritable'):
628 # Python 3.4 and newer
629 _set_inheritable = os.set_inheritable
630else:
631 import fcntl
632
633 def _set_inheritable(fd, inheritable):
634 cloexec_flag = getattr(fcntl, 'FD_CLOEXEC', 1)
635
636 old = fcntl.fcntl(fd, fcntl.F_GETFD)
637 if not inheritable:
638 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
639 else:
640 fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
641
642
Guido van Rossum59691282013-10-30 14:52:03 -0700643class _UnixSubprocessTransport(base_subprocess.BaseSubprocessTransport):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700644
Guido van Rossum59691282013-10-30 14:52:03 -0700645 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700646 stdin_w = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700647 if stdin == subprocess.PIPE:
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700648 # Use a socket pair for stdin, since not all platforms
649 # support selecting read events on the write end of a
650 # socket (which we use in order to detect closing of the
651 # other end). Notably this is needed on AIX, and works
652 # just fine on other platforms.
653 stdin, stdin_w = self._loop._socketpair()
Victor Stinner1e40f102014-12-11 23:30:17 +0100654
655 # Mark the write end of the stdin pipe as non-inheritable,
656 # needed by close_fds=False on Python 3.3 and older
657 # (Python 3.4 implements the PEP 446, socketpair returns
658 # non-inheritable sockets)
659 _set_inheritable(stdin_w.fileno(), False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700660 self._proc = subprocess.Popen(
661 args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
662 universal_newlines=False, bufsize=bufsize, **kwargs)
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700663 if stdin_w is not None:
664 stdin.close()
Victor Stinner2dba23a2014-07-03 00:59:00 +0200665 self._proc.stdin = open(stdin_w.detach(), 'wb', buffering=bufsize)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800666
667
668class AbstractChildWatcher:
669 """Abstract base class for monitoring child processes.
670
671 Objects derived from this class monitor a collection of subprocesses and
672 report their termination or interruption by a signal.
673
674 New callbacks are registered with .add_child_handler(). Starting a new
675 process must be done within a 'with' block to allow the watcher to suspend
676 its activity until the new process if fully registered (this is needed to
677 prevent a race condition in some implementations).
678
679 Example:
680 with watcher:
681 proc = subprocess.Popen("sleep 1")
682 watcher.add_child_handler(proc.pid, callback)
683
684 Notes:
685 Implementations of this class must be thread-safe.
686
687 Since child watcher objects may catch the SIGCHLD signal and call
688 waitpid(-1), there should be only one active object per process.
689 """
690
691 def add_child_handler(self, pid, callback, *args):
692 """Register a new child handler.
693
694 Arrange for callback(pid, returncode, *args) to be called when
695 process 'pid' terminates. Specifying another callback for the same
696 process replaces the previous handler.
697
Victor Stinneracdb7822014-07-14 18:33:40 +0200698 Note: callback() must be thread-safe.
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800699 """
700 raise NotImplementedError()
701
702 def remove_child_handler(self, pid):
703 """Removes the handler for process 'pid'.
704
705 The function returns True if the handler was successfully removed,
706 False if there was nothing to remove."""
707
708 raise NotImplementedError()
709
Guido van Rossum2bcae702013-11-13 15:50:08 -0800710 def attach_loop(self, loop):
711 """Attach the watcher to an event loop.
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800712
Guido van Rossum2bcae702013-11-13 15:50:08 -0800713 If the watcher was previously attached to an event loop, then it is
714 first detached before attaching to the new loop.
715
716 Note: loop may be None.
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800717 """
718 raise NotImplementedError()
719
720 def close(self):
721 """Close the watcher.
722
723 This must be called to make sure that any underlying resource is freed.
724 """
725 raise NotImplementedError()
726
727 def __enter__(self):
728 """Enter the watcher's context and allow starting new processes
729
730 This function must return self"""
731 raise NotImplementedError()
732
733 def __exit__(self, a, b, c):
734 """Exit the watcher's context"""
735 raise NotImplementedError()
736
737
738class BaseChildWatcher(AbstractChildWatcher):
739
Guido van Rossum2bcae702013-11-13 15:50:08 -0800740 def __init__(self):
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800741 self._loop = None
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800742
743 def close(self):
Guido van Rossum2bcae702013-11-13 15:50:08 -0800744 self.attach_loop(None)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800745
746 def _do_waitpid(self, expected_pid):
747 raise NotImplementedError()
748
749 def _do_waitpid_all(self):
750 raise NotImplementedError()
751
Guido van Rossum2bcae702013-11-13 15:50:08 -0800752 def attach_loop(self, loop):
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800753 assert loop is None or isinstance(loop, events.AbstractEventLoop)
754
755 if self._loop is not None:
756 self._loop.remove_signal_handler(signal.SIGCHLD)
757
758 self._loop = loop
759 if loop is not None:
760 loop.add_signal_handler(signal.SIGCHLD, self._sig_chld)
761
762 # Prevent a race condition in case a child terminated
763 # during the switch.
764 self._do_waitpid_all()
765
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800766 def _sig_chld(self):
767 try:
768 self._do_waitpid_all()
Yury Selivanov569efa22014-02-18 18:02:19 -0500769 except Exception as exc:
770 # self._loop should always be available here
771 # as '_sig_chld' is added as a signal handler
772 # in 'attach_loop'
773 self._loop.call_exception_handler({
774 'message': 'Unknown exception in SIGCHLD handler',
775 'exception': exc,
776 })
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800777
778 def _compute_returncode(self, status):
779 if os.WIFSIGNALED(status):
780 # The child process died because of a signal.
781 return -os.WTERMSIG(status)
782 elif os.WIFEXITED(status):
783 # The child process exited (e.g sys.exit()).
784 return os.WEXITSTATUS(status)
785 else:
786 # The child exited, but we don't understand its status.
787 # This shouldn't happen, but if it does, let's just
788 # return that status; perhaps that helps debug it.
789 return status
790
791
792class SafeChildWatcher(BaseChildWatcher):
793 """'Safe' child watcher implementation.
794
795 This implementation avoids disrupting other code spawning processes by
796 polling explicitly each process in the SIGCHLD handler instead of calling
797 os.waitpid(-1).
798
799 This is a safe solution but it has a significant overhead when handling a
800 big number of children (O(n) each time SIGCHLD is raised)
801 """
802
Guido van Rossum2bcae702013-11-13 15:50:08 -0800803 def __init__(self):
804 super().__init__()
805 self._callbacks = {}
806
807 def close(self):
808 self._callbacks.clear()
809 super().close()
810
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800811 def __enter__(self):
812 return self
813
814 def __exit__(self, a, b, c):
815 pass
816
817 def add_child_handler(self, pid, callback, *args):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100818 self._callbacks[pid] = (callback, args)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800819
820 # Prevent a race condition in case the child is already terminated.
821 self._do_waitpid(pid)
822
Guido van Rossum2bcae702013-11-13 15:50:08 -0800823 def remove_child_handler(self, pid):
824 try:
825 del self._callbacks[pid]
826 return True
827 except KeyError:
828 return False
829
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800830 def _do_waitpid_all(self):
831
832 for pid in list(self._callbacks):
833 self._do_waitpid(pid)
834
835 def _do_waitpid(self, expected_pid):
836 assert expected_pid > 0
837
838 try:
839 pid, status = os.waitpid(expected_pid, os.WNOHANG)
840 except ChildProcessError:
841 # The child process is already reaped
842 # (may happen if waitpid() is called elsewhere).
843 pid = expected_pid
844 returncode = 255
845 logger.warning(
846 "Unknown child process pid %d, will report returncode 255",
847 pid)
848 else:
849 if pid == 0:
850 # The child process is still alive.
851 return
852
853 returncode = self._compute_returncode(status)
Victor Stinneracdb7822014-07-14 18:33:40 +0200854 if self._loop.get_debug():
855 logger.debug('process %s exited with returncode %s',
856 expected_pid, returncode)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800857
858 try:
859 callback, args = self._callbacks.pop(pid)
860 except KeyError: # pragma: no cover
861 # May happen if .remove_child_handler() is called
862 # after os.waitpid() returns.
Victor Stinnerb2614752014-08-25 23:20:52 +0200863 if self._loop.get_debug():
864 logger.warning("Child watcher got an unexpected pid: %r",
865 pid, exc_info=True)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800866 else:
867 callback(pid, returncode, *args)
868
869
870class FastChildWatcher(BaseChildWatcher):
871 """'Fast' child watcher implementation.
872
873 This implementation reaps every terminated processes by calling
874 os.waitpid(-1) directly, possibly breaking other code spawning processes
875 and waiting for their termination.
876
877 There is no noticeable overhead when handling a big number of children
878 (O(1) each time a child terminates).
879 """
Guido van Rossum2bcae702013-11-13 15:50:08 -0800880 def __init__(self):
881 super().__init__()
882 self._callbacks = {}
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800883 self._lock = threading.Lock()
884 self._zombies = {}
885 self._forks = 0
886
887 def close(self):
Guido van Rossum2bcae702013-11-13 15:50:08 -0800888 self._callbacks.clear()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800889 self._zombies.clear()
Guido van Rossum2bcae702013-11-13 15:50:08 -0800890 super().close()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800891
892 def __enter__(self):
893 with self._lock:
894 self._forks += 1
895
896 return self
897
898 def __exit__(self, a, b, c):
899 with self._lock:
900 self._forks -= 1
901
902 if self._forks or not self._zombies:
903 return
904
905 collateral_victims = str(self._zombies)
906 self._zombies.clear()
907
908 logger.warning(
909 "Caught subprocesses termination from unknown pids: %s",
910 collateral_victims)
911
912 def add_child_handler(self, pid, callback, *args):
913 assert self._forks, "Must use the context manager"
Guido van Rossumab27a9f2014-01-25 16:32:17 -0800914 with self._lock:
915 try:
916 returncode = self._zombies.pop(pid)
917 except KeyError:
918 # The child is running.
919 self._callbacks[pid] = callback, args
920 return
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800921
Guido van Rossumab27a9f2014-01-25 16:32:17 -0800922 # The child is dead already. We can fire the callback.
923 callback(pid, returncode, *args)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800924
Guido van Rossum2bcae702013-11-13 15:50:08 -0800925 def remove_child_handler(self, pid):
926 try:
927 del self._callbacks[pid]
928 return True
929 except KeyError:
930 return False
931
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800932 def _do_waitpid_all(self):
933 # Because of signal coalescing, we must keep calling waitpid() as
934 # long as we're able to reap a child.
935 while True:
936 try:
937 pid, status = os.waitpid(-1, os.WNOHANG)
938 except ChildProcessError:
939 # No more child processes exist.
940 return
941 else:
942 if pid == 0:
943 # A child process is still alive.
944 return
945
946 returncode = self._compute_returncode(status)
947
Guido van Rossumab27a9f2014-01-25 16:32:17 -0800948 with self._lock:
949 try:
950 callback, args = self._callbacks.pop(pid)
951 except KeyError:
952 # unknown child
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800953 if self._forks:
954 # It may not be registered yet.
955 self._zombies[pid] = returncode
Victor Stinneracdb7822014-07-14 18:33:40 +0200956 if self._loop.get_debug():
957 logger.debug('unknown process %s exited '
958 'with returncode %s',
959 pid, returncode)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800960 continue
Guido van Rossumab27a9f2014-01-25 16:32:17 -0800961 callback = None
Victor Stinneracdb7822014-07-14 18:33:40 +0200962 else:
963 if self._loop.get_debug():
964 logger.debug('process %s exited with returncode %s',
965 pid, returncode)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800966
Guido van Rossumab27a9f2014-01-25 16:32:17 -0800967 if callback is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800968 logger.warning(
969 "Caught subprocess termination from unknown pid: "
970 "%d -> %d", pid, returncode)
971 else:
972 callback(pid, returncode, *args)
973
974
975class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
Victor Stinner70db9e42015-01-09 21:32:05 +0100976 """UNIX event loop policy with a watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800977 _loop_factory = _UnixSelectorEventLoop
978
979 def __init__(self):
980 super().__init__()
981 self._watcher = None
982
983 def _init_watcher(self):
984 with events._lock:
985 if self._watcher is None: # pragma: no branch
Guido van Rossum2bcae702013-11-13 15:50:08 -0800986 self._watcher = SafeChildWatcher()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800987 if isinstance(threading.current_thread(),
988 threading._MainThread):
Guido van Rossum2bcae702013-11-13 15:50:08 -0800989 self._watcher.attach_loop(self._local._loop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800990
991 def set_event_loop(self, loop):
992 """Set the event loop.
993
994 As a side effect, if a child watcher was set before, then calling
Guido van Rossum2bcae702013-11-13 15:50:08 -0800995 .set_event_loop() from the main thread will call .attach_loop(loop) on
996 the child watcher.
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800997 """
998
999 super().set_event_loop(loop)
1000
1001 if self._watcher is not None and \
1002 isinstance(threading.current_thread(), threading._MainThread):
Guido van Rossum2bcae702013-11-13 15:50:08 -08001003 self._watcher.attach_loop(loop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001004
1005 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +02001006 """Get the watcher for child processes.
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001007
1008 If not yet set, a SafeChildWatcher object is automatically created.
1009 """
1010 if self._watcher is None:
1011 self._init_watcher()
1012
1013 return self._watcher
1014
1015 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +02001016 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001017
1018 assert watcher is None or isinstance(watcher, AbstractChildWatcher)
1019
1020 if self._watcher is not None:
1021 self._watcher.close()
1022
1023 self._watcher = watcher
1024
1025SelectorEventLoop = _UnixSelectorEventLoop
1026DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy