cpython/Lib/multiprocessing/process.py

299 lines
7.8 KiB
Python
Raw Normal View History

#
# Module providing the `Process` class which emulates `threading.Thread`
#
# multiprocessing/process.py
#
# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
#
__all__ = ['Process', 'current_process', 'active_children']
#
# Imports
#
import os
import sys
import signal
import itertools
#
#
#
try:
ORIGINAL_DIR = os.path.abspath(os.getcwd())
except OSError:
ORIGINAL_DIR = None
#
# Public functions
#
def current_process():
'''
Return process object representing the current process
'''
return _current_process
def active_children():
'''
Return list of process objects corresponding to live child processes
'''
_cleanup()
return list(_current_process._children)
#
#
#
def _cleanup():
# check for processes which have finished
for p in list(_current_process._children):
if p._popen.poll() is not None:
_current_process._children.discard(p)
#
# The `Process` class
#
class Process(object):
'''
Process objects represent activity that is run in a separate process
The class is analagous to `threading.Thread`
'''
_Popen = None
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
assert group is None, 'group argument must be None for now'
count = next(_current_process._counter)
self._identity = _current_process._identity + (count,)
self._authkey = _current_process._authkey
self._daemonic = _current_process._daemonic
self._tempdir = _current_process._tempdir
self._parent_pid = os.getpid()
self._popen = None
self._target = target
self._args = tuple(args)
self._kwargs = dict(kwargs)
self._name = name or type(self).__name__ + '-' + \
':'.join(str(i) for i in self._identity)
def run(self):
'''
Method to be run in sub-process; can be overridden in sub-class
'''
if self._target:
self._target(*self._args, **self._kwargs)
def start(self):
'''
Start child process
'''
assert self._popen is None, 'cannot start a process twice'
assert self._parent_pid == os.getpid(), \
'can only start a process object created by current process'
assert not _current_process._daemonic, \
'daemonic processes are not allowed to have children'
_cleanup()
if self._Popen is not None:
Popen = self._Popen
else:
from .forking import Popen
self._popen = Popen(self)
_current_process._children.add(self)
def terminate(self):
'''
Terminate process; sends SIGTERM signal or uses TerminateProcess()
'''
self._popen.terminate()
def join(self, timeout=None):
'''
Wait until child process terminates
'''
assert self._parent_pid == os.getpid(), 'can only join a child process'
assert self._popen is not None, 'can only join a started process'
res = self._popen.wait(timeout)
if res is not None:
_current_process._children.discard(self)
def is_alive(self):
'''
Return whether process is alive
'''
if self is _current_process:
return True
assert self._parent_pid == os.getpid(), 'can only test a child process'
if self._popen is None:
return False
self._popen.poll()
return self._popen.returncode is None
@property
def name(self):
return self._name
@name.setter
def name(self, name):
assert isinstance(name, str), 'name must be a string'
self._name = name
@property
def daemon(self):
'''
Return whether process is a daemon
'''
return self._daemonic
@daemon.setter
def daemon(self, daemonic):
'''
Set whether process is a daemon
'''
assert self._popen is None, 'process has already started'
self._daemonic = daemonic
@property
def authkey(self):
return self._authkey
@authkey.setter
def authkey(self, authkey):
'''
Set authorization key of process
'''
self._authkey = AuthenticationString(authkey)
@property
def exitcode(self):
'''
Return exit code of process or `None` if it has yet to stop
'''
if self._popen is None:
return self._popen
return self._popen.poll()
@property
def ident(self):
'''
Note: only the relevant parts of r79474 are merged. Merged revisions 78793,78798-78799,78977,79095,79196,79474 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/py3k ................ r78793 | florent.xicluna | 2010-03-08 13:25:35 +0100 (lun, 08 mar 2010) | 2 lines Fix macpath to deal with bytes ................ r78798 | florent.xicluna | 2010-03-08 14:32:17 +0100 (lun, 08 mar 2010) | 18 lines Merged revisions 78777,78787,78790 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r78777 | florent.xicluna | 2010-03-08 00:49:03 +0100 (lun, 08 mar 2010) | 4 lines Backport the Popen.poll() protection from subprocess to multiprocessing. See #1731717. It should fix transient failures on test_multiprocessing. ........ r78787 | florent.xicluna | 2010-03-08 08:21:16 +0100 (lun, 08 mar 2010) | 2 lines Don't fail on a debug() statement, if the worker PID is (still) None. ........ r78790 | florent.xicluna | 2010-03-08 12:01:39 +0100 (lun, 08 mar 2010) | 2 lines On finalize, don't try to join not started process. ........ ................ r78799 | florent.xicluna | 2010-03-08 15:44:41 +0100 (lun, 08 mar 2010) | 2 lines Fix ntpath abspath to deal with bytes. ................ r78977 | florent.xicluna | 2010-03-15 14:14:39 +0100 (lun, 15 mar 2010) | 2 lines Fix \xhh specs, #1889. (an oversight of r60193, r60210). ................ r79095 | florent.xicluna | 2010-03-19 15:40:31 +0100 (ven, 19 mar 2010) | 2 lines Rename test.test_support to test.support for 3.x. ................ r79196 | florent.xicluna | 2010-03-21 13:29:50 +0100 (dim, 21 mar 2010) | 9 lines Merged revisions 79195 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r79195 | florent.xicluna | 2010-03-21 13:27:20 +0100 (dim, 21 mar 2010) | 2 lines Issue #8179: Fix macpath.realpath() on a non-existing path. ........ ................ r79474 | florent.xicluna | 2010-03-28 01:25:02 +0100 (dim, 28 mar 2010) | 33 lines Merged revisions 79297,79310,79382,79425-79427,79450 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r79297 | florent.xicluna | 2010-03-22 18:18:18 +0100 (lun, 22 mar 2010) | 2 lines #7668: Fix test_httpservers failure when sys.executable contains non-ASCII bytes. ........ r79310 | florent.xicluna | 2010-03-22 23:52:11 +0100 (lun, 22 mar 2010) | 2 lines Issue #8205: Remove the "Modules" directory from sys.path when Python is running from the build directory (POSIX only). ........ r79382 | florent.xicluna | 2010-03-24 20:33:25 +0100 (mer, 24 mar 2010) | 2 lines Skip tests which depend on multiprocessing.sharedctypes, if _ctypes is not available. ........ r79425 | florent.xicluna | 2010-03-25 21:32:07 +0100 (jeu, 25 mar 2010) | 2 lines Syntax cleanup `== None` -> `is None` ........ r79426 | florent.xicluna | 2010-03-25 21:33:49 +0100 (jeu, 25 mar 2010) | 2 lines #8207: Fix test_pep277 on OS X ........ r79427 | florent.xicluna | 2010-03-25 21:39:10 +0100 (jeu, 25 mar 2010) | 2 lines Fix test_unittest and test_warnings when running "python -Werror -m test.regrtest" ........ r79450 | florent.xicluna | 2010-03-26 20:32:44 +0100 (ven, 26 mar 2010) | 2 lines Ensure that the failed or unexpected tests are sorted before printing. ........ ................
2010-03-28 08:42:38 -03:00
Return identifier (PID) of process or `None` if it has yet to start
'''
if self is _current_process:
return os.getpid()
else:
return self._popen and self._popen.pid
pid = ident
def __repr__(self):
if self is _current_process:
status = 'started'
elif self._parent_pid != os.getpid():
status = 'unknown'
elif self._popen is None:
status = 'initial'
else:
if self._popen.poll() is not None:
status = self.exitcode
else:
status = 'started'
if type(status) is int:
if status == 0:
status = 'stopped'
else:
status = 'stopped[%s]' % _exitcode_to_name.get(status, status)
return '<%s(%s, %s%s)>' % (type(self).__name__, self._name,
status, self._daemonic and ' daemon' or '')
##
def _bootstrap(self):
from . import util
global _current_process
try:
self._children = set()
self._counter = itertools.count(1)
if sys.stdin is not None:
try:
sys.stdin.close()
sys.stdin = open(os.devnull)
except (OSError, ValueError):
pass
_current_process = self
util._finalizer_registry.clear()
util._run_after_forkers()
util.info('child process calling self.run()')
try:
self.run()
exitcode = 0
finally:
util._exit_function()
except SystemExit as e:
if not e.args:
exitcode = 1
elif type(e.args[0]) is int:
exitcode = e.args[0]
else:
sys.stderr.write(e.args[0] + '\n')
sys.stderr.flush()
exitcode = 1
except:
exitcode = 1
import traceback
sys.stderr.write('Process %s:\n' % self.name)
sys.stderr.flush()
traceback.print_exc()
util.info('process exiting with exitcode %d' % exitcode)
return exitcode
#
# We subclass bytes to avoid accidental transmission of auth keys over network
#
class AuthenticationString(bytes):
def __reduce__(self):
from .forking import Popen
if not Popen.thread_is_spawning():
raise TypeError(
'Pickling an AuthenticationString object is '
'disallowed for security reasons'
)
return AuthenticationString, (bytes(self),)
#
# Create object representing the main process
#
class _MainProcess(Process):
def __init__(self):
self._identity = ()
self._daemonic = False
self._name = 'MainProcess'
self._parent_pid = None
self._popen = None
self._counter = itertools.count(1)
self._children = set()
self._authkey = AuthenticationString(os.urandom(32))
self._tempdir = None
_current_process = _MainProcess()
del _MainProcess
#
# Give names to some return codes
#
_exitcode_to_name = {}
for name, signum in list(signal.__dict__.items()):
if name[:3]=='SIG' and '_' not in name:
_exitcode_to_name[-signum] = name