blob: c1cb36f4c704d8d83c5757cfa731d859426e2eef [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001#
2# Module providing the `Process` class which emulates `threading.Thread`
3#
4# multiprocessing/process.py
5#
R. David Murray3fc969a2010-12-14 01:38:16 +00006# Copyright (c) 2006-2008, R Oudkerk
Richard Oudkerk3e268aa2012-04-30 12:13:55 +01007# Licensed to PSF under a Contributor Agreement.
Benjamin Petersone711caf2008-06-11 16:44:04 +00008#
9
10__all__ = ['Process', 'current_process', 'active_children']
11
12#
13# Imports
14#
15
16import os
17import sys
18import signal
19import itertools
Antoine Pitrouc081c0c2011-07-15 22:12:24 +020020from _weakrefset import WeakSet
Benjamin Petersone711caf2008-06-11 16:44:04 +000021
22#
23#
24#
25
26try:
27 ORIGINAL_DIR = os.path.abspath(os.getcwd())
28except OSError:
29 ORIGINAL_DIR = None
30
Benjamin Petersone711caf2008-06-11 16:44:04 +000031#
32# Public functions
33#
34
35def current_process():
36 '''
37 Return process object representing the current process
38 '''
39 return _current_process
40
41def active_children():
42 '''
43 Return list of process objects corresponding to live child processes
44 '''
45 _cleanup()
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010046 return list(_children)
Benjamin Petersone711caf2008-06-11 16:44:04 +000047
48#
49#
50#
51
52def _cleanup():
53 # check for processes which have finished
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010054 for p in list(_children):
Benjamin Petersone711caf2008-06-11 16:44:04 +000055 if p._popen.poll() is not None:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010056 _children.discard(p)
Benjamin Petersone711caf2008-06-11 16:44:04 +000057
58#
59# The `Process` class
60#
61
62class Process(object):
63 '''
64 Process objects represent activity that is run in a separate process
65
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010066 The class is analogous to `threading.Thread`
Benjamin Petersone711caf2008-06-11 16:44:04 +000067 '''
68 _Popen = None
69
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +000070 def __init__(self, group=None, target=None, name=None, args=(), kwargs={},
71 *, daemon=None):
Benjamin Petersone711caf2008-06-11 16:44:04 +000072 assert group is None, 'group argument must be None for now'
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010073 count = next(_process_counter)
Benjamin Petersone711caf2008-06-11 16:44:04 +000074 self._identity = _current_process._identity + (count,)
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010075 self._config = _current_process._config.copy()
Benjamin Petersone711caf2008-06-11 16:44:04 +000076 self._parent_pid = os.getpid()
77 self._popen = None
78 self._target = target
79 self._args = tuple(args)
80 self._kwargs = dict(kwargs)
81 self._name = name or type(self).__name__ + '-' + \
82 ':'.join(str(i) for i in self._identity)
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010083 if daemon is not None:
84 self.daemon = daemon
Antoine Pitrouc081c0c2011-07-15 22:12:24 +020085 _dangling.add(self)
Benjamin Petersone711caf2008-06-11 16:44:04 +000086
87 def run(self):
88 '''
89 Method to be run in sub-process; can be overridden in sub-class
90 '''
91 if self._target:
92 self._target(*self._args, **self._kwargs)
93
94 def start(self):
95 '''
96 Start child process
97 '''
98 assert self._popen is None, 'cannot start a process twice'
99 assert self._parent_pid == os.getpid(), \
100 'can only start a process object created by current process'
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100101 assert not _current_process._config.get('daemon'), \
Benjamin Petersone711caf2008-06-11 16:44:04 +0000102 'daemonic processes are not allowed to have children'
103 _cleanup()
104 if self._Popen is not None:
105 Popen = self._Popen
106 else:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100107 from .popen import Popen
Benjamin Petersone711caf2008-06-11 16:44:04 +0000108 self._popen = Popen(self)
Antoine Pitrou176f07d2011-06-06 19:35:31 +0200109 self._sentinel = self._popen.sentinel
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100110 _children.add(self)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000111
112 def terminate(self):
113 '''
114 Terminate process; sends SIGTERM signal or uses TerminateProcess()
115 '''
116 self._popen.terminate()
117
118 def join(self, timeout=None):
119 '''
120 Wait until child process terminates
121 '''
122 assert self._parent_pid == os.getpid(), 'can only join a child process'
123 assert self._popen is not None, 'can only join a started process'
124 res = self._popen.wait(timeout)
125 if res is not None:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100126 _children.discard(self)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000127
128 def is_alive(self):
129 '''
130 Return whether process is alive
131 '''
132 if self is _current_process:
133 return True
134 assert self._parent_pid == os.getpid(), 'can only test a child process'
135 if self._popen is None:
136 return False
137 self._popen.poll()
138 return self._popen.returncode is None
139
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000140 @property
141 def name(self):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000142 return self._name
143
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000144 @name.setter
145 def name(self, name):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000146 assert isinstance(name, str), 'name must be a string'
147 self._name = name
148
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000149 @property
150 def daemon(self):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000151 '''
152 Return whether process is a daemon
153 '''
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100154 return self._config.get('daemon', False)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000155
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000156 @daemon.setter
157 def daemon(self, daemonic):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000158 '''
159 Set whether process is a daemon
160 '''
161 assert self._popen is None, 'process has already started'
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100162 self._config['daemon'] = daemonic
Benjamin Petersone711caf2008-06-11 16:44:04 +0000163
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000164 @property
165 def authkey(self):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100166 return self._config['authkey']
Benjamin Petersone711caf2008-06-11 16:44:04 +0000167
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000168 @authkey.setter
169 def authkey(self, authkey):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000170 '''
171 Set authorization key of process
172 '''
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100173 self._config['authkey'] = AuthenticationString(authkey)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000174
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000175 @property
176 def exitcode(self):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000177 '''
178 Return exit code of process or `None` if it has yet to stop
179 '''
180 if self._popen is None:
181 return self._popen
182 return self._popen.poll()
183
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000184 @property
185 def ident(self):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000186 '''
Florent Xiclunab519d232010-03-04 16:10:55 +0000187 Return identifier (PID) of process or `None` if it has yet to start
Benjamin Petersone711caf2008-06-11 16:44:04 +0000188 '''
189 if self is _current_process:
190 return os.getpid()
191 else:
192 return self._popen and self._popen.pid
193
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000194 pid = ident
Benjamin Petersone711caf2008-06-11 16:44:04 +0000195
Antoine Pitrou176f07d2011-06-06 19:35:31 +0200196 @property
197 def sentinel(self):
198 '''
199 Return a file descriptor (Unix) or handle (Windows) suitable for
200 waiting for process termination.
201 '''
202 try:
203 return self._sentinel
204 except AttributeError:
205 raise ValueError("process not started")
206
Benjamin Petersone711caf2008-06-11 16:44:04 +0000207 def __repr__(self):
208 if self is _current_process:
209 status = 'started'
210 elif self._parent_pid != os.getpid():
211 status = 'unknown'
212 elif self._popen is None:
213 status = 'initial'
214 else:
215 if self._popen.poll() is not None:
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000216 status = self.exitcode
Benjamin Petersone711caf2008-06-11 16:44:04 +0000217 else:
218 status = 'started'
219
220 if type(status) is int:
221 if status == 0:
222 status = 'stopped'
223 else:
224 status = 'stopped[%s]' % _exitcode_to_name.get(status, status)
225
226 return '<%s(%s, %s%s)>' % (type(self).__name__, self._name,
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100227 status, self.daemon and ' daemon' or '')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000228
229 ##
230
231 def _bootstrap(self):
232 from . import util
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100233 global _current_process, _process_counter, _children
Benjamin Petersone711caf2008-06-11 16:44:04 +0000234
235 try:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100236 _process_counter = itertools.count(1)
237 _children = set()
Amaury Forgeot d'Arc768008c2008-08-20 09:04:46 +0000238 if sys.stdin is not None:
239 try:
Alexandre Vassalottic57a84f2009-07-17 12:07:01 +0000240 sys.stdin.close()
241 sys.stdin = open(os.devnull)
Amaury Forgeot d'Arc768008c2008-08-20 09:04:46 +0000242 except (OSError, ValueError):
243 pass
Victor Stinner0f83b152011-06-17 12:31:49 +0200244 old_process = _current_process
Benjamin Petersone711caf2008-06-11 16:44:04 +0000245 _current_process = self
Victor Stinner0f83b152011-06-17 12:31:49 +0200246 try:
247 util._finalizer_registry.clear()
248 util._run_after_forkers()
249 finally:
250 # delay finalization of the old process object until after
251 # _run_after_forkers() is executed
252 del old_process
Benjamin Petersone711caf2008-06-11 16:44:04 +0000253 util.info('child process calling self.run()')
254 try:
255 self.run()
256 exitcode = 0
257 finally:
258 util._exit_function()
259 except SystemExit as e:
260 if not e.args:
261 exitcode = 1
Richard Oudkerk29471de2012-06-06 19:04:57 +0100262 elif isinstance(e.args[0], int):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000263 exitcode = e.args[0]
264 else:
Richard Oudkerk29471de2012-06-06 19:04:57 +0100265 sys.stderr.write(str(e.args[0]) + '\n')
266 exitcode = 0 if isinstance(e.args[0], str) else 1
Benjamin Petersone711caf2008-06-11 16:44:04 +0000267 except:
268 exitcode = 1
269 import traceback
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000270 sys.stderr.write('Process %s:\n' % self.name)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000271 traceback.print_exc()
Antoine Pitrou84a0fbf2012-01-27 10:52:37 +0100272 finally:
273 util.info('process exiting with exitcode %d' % exitcode)
274 sys.stdout.flush()
275 sys.stderr.flush()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000276
Benjamin Petersone711caf2008-06-11 16:44:04 +0000277 return exitcode
278
279#
280# We subclass bytes to avoid accidental transmission of auth keys over network
281#
282
283class AuthenticationString(bytes):
284 def __reduce__(self):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100285 from .popen import get_spawning_popen
286 if get_spawning_popen() is None:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000287 raise TypeError(
288 'Pickling an AuthenticationString object is '
289 'disallowed for security reasons'
290 )
291 return AuthenticationString, (bytes(self),)
292
293#
294# Create object representing the main process
295#
296
297class _MainProcess(Process):
298
299 def __init__(self):
300 self._identity = ()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000301 self._name = 'MainProcess'
302 self._parent_pid = None
303 self._popen = None
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100304 self._config = {'authkey': AuthenticationString(os.urandom(32)),
305 'semprefix': 'mp'}
306 # Note that some versions of FreeBSD only allow named
307 # semaphores to have names of up to 14 characters. Therfore
308 # we choose a short prefix.
309
Benjamin Petersone711caf2008-06-11 16:44:04 +0000310
311_current_process = _MainProcess()
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100312_process_counter = itertools.count(1)
313_children = set()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000314del _MainProcess
315
316#
317# Give names to some return codes
318#
319
320_exitcode_to_name = {}
321
322for name, signum in list(signal.__dict__.items()):
323 if name[:3]=='SIG' and '_' not in name:
324 _exitcode_to_name[-signum] = name
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200325
326# For debug and leak testing
327_dangling = WeakSet()